php中文和unicode互轉


     unicode轉中文時可以使用json_decode()函數實現。

        中文轉unicode時需要對字符串轉換成UCS-4編碼,再轉成16進制,再從16進制轉換成10進制加上&#前綴來實現中文轉unicode編碼。

一、unicode轉中文

php
  1. <?php
  2. //unicode轉中文
  3. function unicodeDecode($unicode_str){
  4.     $json = '{"str":"'.$unicode_str.'"}';
  5.     $arr = json_decode($json,true);
  6.     if(empty($arr)) return '';
  7.     return $arr['str'];
  8. }
  9.  
  10. $unicode_str = "\u4e2d\u56fd";
  11. echo unicodeDecode($unicode_str);

二、中文轉unicode

php
  1. //中文轉unicode
  2. function UnicodeEncode($str){
  3.     //split word
  4.     preg_match_all('/./u',$str,$matches);
  5.  
  6.     $unicodeStr = "";
  7.     foreach($matches[0] as $m){
  8.         //拼接
  9.         $unicodeStr .= "&#".base_convert(bin2hex(iconv('UTF-8',"UCS-4",$m)),16,10);
  10.     }
  11.     return $unicodeStr;
  12. }
  13.  
  14. $str = "新浪微博";
  15. echo UnicodeEncode($str);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM