码迷,mamicode.com
首页 > Web开发 > 详细

php中文和unicode互转

时间:2019-12-19 12:41:02      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:return   新浪   amp   ucs   hex   match   编码   字符   UNC   

     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);

php中文和unicode互转

标签:return   新浪   amp   ucs   hex   match   编码   字符   UNC   

原文地址:https://www.cnblogs.com/qiuhao/p/12066964.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!