php &#编码/php unicode转码/php &#数字编码

今天使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 ,但是HTML可识别的, 比如 企业站

function convertToHtmlHexUnicode($string) {  
    $unicodeArray = [];  
    // 遍历字符串中的每个字符  
    for ($i = 0; $i < mb_strlen($string, 'UTF-8'); $i++) {  
        // 获取每个字符  
        $char = mb_substr($string, $i, 1, 'UTF-8');  
        // 获取该字符的 Unicode 码点  
        $unicode = mb_ord($char, 'UTF-8');  // 获取字符的 Unicode 码点  
        // 格式化为 HTML 16 进制 Unicode 编码  
        $unicodeArray[] = sprintf("&#x%04x;", $unicode);  
    }  
    // 返回连接的 Unicode 字符串  
    return implode('', $unicodeArray);  
}  

 

 

 

 

3: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解码结果:“新浪微博”

 

 

总结:unicode的编码解码虽然代码不多,但是真要你写出来的话,一般情况下我们还不会,因此做个笔记记下来是一个不错的选择,如果觉得帮助到了你,可以点击下方的分享按钮,或者收藏起来哦!

 
posted @ 2019-10-07 16:14  山上小和尚  阅读(2552)  评论(0)    收藏  举报