Unicode character in PHP string

前端 未结 8 1750
生来不讨喜
生来不讨喜 2020-11-22 14:17

This question looks embarrassingly simple, but I haven\'t been able to find an answer.

What is the PHP equivalent to the following C# line of code?

s         


        
8条回答
  •  -上瘾入骨i
    2020-11-22 14:44

    PHP does not know these Unicode escape sequences. But as unknown escape sequences remain unaffected, you can write your own function that converts such Unicode escape sequences:

    function unicodeString($str, $encoding=null) {
        if (is_null($encoding)) $encoding = ini_get('mbstring.internal_encoding');
        return preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/u', create_function('$match', 'return mb_convert_encoding(pack("H*", $match[1]), '.var_export($encoding, true).', "UTF-16BE");'), $str);
    }
    

    Or with an anonymous function expression instead of create_function:

    function unicodeString($str, $encoding=null) {
        if (is_null($encoding)) $encoding = ini_get('mbstring.internal_encoding');
        return preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/u', function($match) use ($encoding) {
            return mb_convert_encoding(pack('H*', $match[1]), $encoding, 'UTF-16BE');
        }, $str);
    }
    

    Its usage:

    $str = unicodeString("\u1000");
    

提交回复
热议问题