MENU

PHP小技巧之UNICODE编码转中文汉字

May 20, 2019 • 已被 199 位童鞋围观过 • 代码分享

今天使PHP开发用到了Unicode的解码,以下方法可以将Unicode编码的中文转换成utf8编码的中文,且对原来就是utf8编码的中文没影响:

php 5.X 的版本

//把unicode转化成中文
function decodeUnicode($str){
    return preg_replace_callback('/\\\\u([0-9a-f]{4})/i',
        create_function(
            '$matches',
            'return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");'
        ),
        $str);
}

php 7.2 以上的版本 由于自PHP 7.2起,函数create_function已被弃用。更新为匿名函数

//UNICODE编码转中文汉字
function decodeUnicode($str){
    return preg_replace_callback('/\\\\u([0-9a-f]{4})/i',
        function($matches) {
            return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");
        },
        $str);
}
Last Modified: September 28, 2023