How to decode Unicode escape sequences like “\u00ed” to proper UTF-8 encoded characters?

后端 未结 7 933
傲寒
傲寒 2020-11-22 01:01

Is there a function in PHP that can decode Unicode escape sequences like \"\\u00ed\" to \"í\" and all other similar occurrences?

I found si

7条回答
  •  春和景丽
    2020-11-22 01:21

    Try this:

    $str = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/', function ($match) {
        return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
    }, $str);
    

    In case it's UTF-16 based C/C++/Java/Json-style:

    $str = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/', function ($match) {
        return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UTF-16BE');
    }, $str);
    

提交回复
热议问题