PHP Unicode编码与解码_Unicode转中文_中文转Unicode字符

180it 2020-11-19 AM 2196℃ 0条

今天使PHP开发用到了Unicode的编码与解码,将unicode转为中文,再将中文转Unicode这样的操作是非常常见的,所以小编将这两个unicode中文互转函数给作为一个笔记保存起来,非常的简单,会用就行了。

1:下面来看PHP Unicode编码方法,将中文转为Unicode字符,例如将新浪微博转换为unicode字符串,代码如下:

function UnicodeEncode($str){
    //split word
    preg_match_all('/./u',$str,$matches);
 
    $unicodeStr = "";
    foreach($matches[0] as $m){
        //拼接
        $unicodeStr .= "&#".base_convert(bin2hex(iconv('UTF-8',"UCS-4",$m)),16,10);
    }
    return $unicodeStr;
}
 
$str = "新浪微博";
echo UnicodeEncode($str);

Unicode编码输出字符串:"\u65b0\u6d6a\u5fae\u535a"

2:unicode解码方法,将上面的unicode字符转换成中文,代码如下:

function unicodeDecode($unicode_str){
    $json = '{"str":"'.$unicode_str.'"}';
    $arr = json_decode($json,true);
    if(empty($arr)) return '';
    return $arr['str'];
}
 
$unicode_str = "\u65b0\u6d6a\u5fae\u535a";
echo unicodeDecode($unicode_str);

Unicode解码结果:“新浪微博”

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

PHP Unicode编码与解码_Unicode转中文_中文转Unicode字符