首页 > 解决方案 > php函数返回空

问题描述

(首先,英语不是我的母语,如有词汇或语法错误请见谅……其次,我不是专业程序员,我是通过阅读在线教程学习PHP的)

我编写了一个 php 函数,用它们的 html 代码替换 unicode 字符的子字符串(通过形式 \uXXXX)。这是功能:

function unicode_to_html($var){
    if(isset($var) && !empty($var) ) 
    {
        $pos = strpos($var, '\u');
        $hexa_code = substr($var, $pos+2, 4) ;
        $unicode_string = '\u' . $hexa_code ;
        $deci_code = hexdec($hexa_code) ;
        $html_string = '&#' . $deci_code . ';' ;
        $var = str_replace($unicode_string,  $html_string, $var) ;
        if (strpos($var, '\u') !== false) {
            unicode_to_html($var);
        } else {
            $output = $var ;
            echo 'result of the function unicode_to_html : ' . $output . '<br />' ;
            try {
                return $output ;
            }
            catch (Exception $e) {
                echo 'Exception : ',  $e->getMessage(), "\n";
            }
        }
    } 
    else 
    {
        return $var ;
    }
}

我称这个函数如下:

$var = 'Velibor \u010Coli\u0107'; 
echo 'input : ' . $var . '<br />' ;
$var2 = unicode_to_html($var) ;
echo 'output : ' . $var2 . '<br />' ;

但是虽然函数中的“echo”确实显示了想要的结果,但该函数似乎返回一个空(或 null ?)字符串

input : Velibor \u010Coli\u0107
result of the function unicode_to_html : Velibor Čolić 
output :

我不明白为什么。对于专业程序员来说,这可能是显而易见的,但我不是......

感谢您的帮助。

标签: phpfunction

解决方案


现在你没有从函数返回任何东西,阅读更多关于递归函数的信息,只需添加return到函数:

if (strpos($var, '\u') !== false) {
    return unicode_to_html($var);
}

推荐阅读