简体   繁体   中英

php function returns empty

(First of all, English is not my native language, so please excuse any error in vocabulary or grammar... Second, I'm not a professionnal programmer, I learned PHP by reading online tutorials)

I wrote a php function to replace substrings of unicode characters (by the form \\uXXXX) by their html code. Here's the function :

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 ;
    }
}

I call this function as follows :

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

but while the "echo" within the function does displays the wanted result, the function seems to return an empty (or null ?) string

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

and I don't see why. It may be something obvious for a professionnal programmer, but this I am not...

Thank you for your help.

Now you not returning anything from function, read more about recursive functions, just add return to function:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM