首頁  >  文章  >  後端開發  >  PHP解碼unicode編碼

PHP解碼unicode編碼

不言
不言原創
2018-04-24 13:54:538694瀏覽

这篇文章主要介绍了PHP解码unicode编码  ,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下

function unicode_decode($name)  {  
    //方法一
    $name = str_replace("\\\\u","\u",$name);    $json = '{"str":"'.$name.'"}';    $arr = json_decode($json,true);    if(empty($arr)) return ''; 
    return $arr['str'];    //方法二
    // 转换编码,将Unicode编码转换成可以浏览的utf-8编码  
    $pattern = '/([\w]+)|(\\\u([\w]{4}))/i';  
    preg_match_all($pattern, $name, $matches);  
    if (!empty($matches))  
    {  
        $name = '';  
        for ($j = 0; $j < count($matches[0]); $j++)  
        {  
            $str = $matches[0][$j];  
            if (strpos($str, &#39;\\u&#39;) === 0)  
            {  
                $code = base_convert(substr($str, 2, 2), 16, 10);  
                $code2 = base_convert(substr($str, 4), 16, 10);  
                $c = chr($code).chr($code2);  
                $c = iconv(&#39;UCS-2&#39;, &#39;UTF-8&#39;, $c);  
                $name .= $c;  
            }  
            else  
            {  
                $name .= $str;  
            }  
        }  
    }  
    return $name;  
}


以下是网上找的方法:
方案A(稳定版+推荐):

function replace_unicode_escape_sequence($match) {
  return mb_convert_encoding(pack(&#39;H*&#39;, $match[1]), &#39;UTF-8&#39;, &#39;UCS-2BE&#39;);
}$name = &#39;\u65b0\u6d6a\u5fae\u535a&#39;;$str = preg_replace_callback(&#39;/\\\\u([0-9a-f]{4})/i&#39;, &#39;replace_unicode_escape_sequence&#39;, $name);echo $str; //输出: 新浪微博
//咱将上述方案A给封装起来~~~(方案A稳定版+升级+推荐)class Helper_Tool{
  static function unicodeDecode($data)
  {  
    function replace_unicode_escape_sequence($match) {
      return mb_convert_encoding(pack(&#39;H*&#39;, $match[1]), &#39;UTF-8&#39;, &#39;UCS-2BE&#39;);
    }  

    $rs = preg_replace_callback(&#39;/\\\\u([0-9a-f]{4})/i&#39;, &#39;replace_unicode_escape_sequence&#39;, $data);    return $rs;
  }  
}//调用$name = &#39;\u65b0\u6d6a\u5fae\u535a&#39;;$data = Helper_Tool::unicodeDecode($name); //输出新浪微博

方案B(次推荐):

<?phpfunction unicodeDecode($name){
  $json = &#39;{"str":"&#39;.$name.&#39;"}&#39;;  $arr = json_decode($json,true);  if(empty($arr)) return &#39;&#39;; 
  return $arr[&#39;str&#39;];
}$name = &#39;\u65b0\u6d6a\u5fae\u535a&#39;;echo unicodeDecode($name); //输出: 新浪微博

相关推荐:

php解码js使用escape转码的函数

以上是PHP解碼unicode編碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn