找回密码
 注册加入

扫一扫,极速登录

QQ登录

只需一步,快速开始

搜索
查看: 6416|回复: 0

php中文汉字转Unicode编码,Unicode转中文的函数

[复制链接]
TA的专栏
发表于 2012-12-16 17:04:06 | 显示全部楼层 |阅读模式
  1. /**
  2. * $str 原始中文字符串
  3. * $encoding 原始字符串的编码,默认GBK
  4. * $prefix 编码后的前缀,默认"&#"
  5. * $postfix 编码后的后缀,默认";"
  6. */
  7. function unicode_encode($str, $encoding = 'GBK', $prefix = '&#', $postfix = ';') {
  8.     $str = iconv($encoding, 'UCS-2', $str);
  9.     $arrstr = str_split($str, 2);
  10.     $unistr = '';
  11.     for($i = 0, $len = count($arrstr); $i < $len; $i++) {
  12.         $dec = hexdec(bin2hex($arrstr[$i]));
  13.         $unistr .= $prefix . $dec . $postfix;
  14.     }
  15.     return $unistr;
  16. }
复制代码
  1. /**
  2. * $str Unicode编码后的字符串
  3. * $decoding 原始字符串的编码,默认GBK
  4. * $prefix 编码字符串的前缀,默认"&#"
  5. * $postfix 编码字符串的后缀,默认";"
  6. */
  7. function unicode_decode($unistr, $encoding = 'GBK', $prefix = '&#', $postfix = ';') {
  8.     $arruni = explode($prefix, $unistr);
  9.     $unistr = '';
  10.     for($i = 1, $len = count($arruni); $i < $len; $i++) {
  11.         if (strlen($postfix) > 0) {
  12.             $arruni[$i] = substr($arruni[$i], 0, strlen($arruni[$i]) - strlen($postfix));
  13.         }
  14.         $temp = intval($arruni[$i]);
  15.         $unistr .= ($temp < 256) ? chr(0) . chr($temp) : chr($temp / 256) . chr($temp % 256);
  16.     }
  17.     return iconv('UCS-2', $encoding, $unistr);
  18. }
复制代码
  1. //GBK字符串测试
  2. $str = '<b>哈哈</b>';
  3. echo $str.'
  4. ';

  5. $unistr = unicode_encode($str);
  6. echo $unistr.'
  7. '; // <b>哈哈</b>

  8. $str2 = unicode_decode($unistr);
  9. echo $str2.'
  10. '; //<b>哈哈</b>

  11. //UTF-8字符串测试
  12. $utf8_str = iconv('GBK', 'UTF-8', $str);
  13. echo $utf8_str.'
  14. '; // <b>鍝堝搱</b> 注:UTF在GBK下显示的乱码!可切换浏览器的编码测试

  15. $utf8_unistr = unicode_encode($utf8_str, 'UTF-8');
  16. echo $utf8_unistr.'
  17. '; // <b>哈哈</b>

  18. $utf8_str2 = unicode_decode($utf8_unistr, 'UTF-8');
  19. echo $utf8_str2.'
  20. '; // <b>鍝堝搱</b>

  21. //其它后缀、前缀测试
  22. $prefix_unistr = unicode_encode($str, 'GBK', "\\u", '');
  23. echo $prefix_unistr.'
  24. '; // \u60\u98\u62\u21704\u21704\u60\u47\u98\u62

  25. $profix_unistr2 = unicode_decode($prefix_unistr, 'GBK', "\\u", '');
  26. echo $profix_unistr2.'
  27. '; //<b>哈哈</b>
复制代码
您需要登录后才可以回帖 登录 | 注册加入  

本版积分规则

Archiver|手机版|小黑屋|Discuz!扩展中心 ( 浙ICP备14042422号-1 )|网站地图QQ机器人

GMT+8, 2024-3-29 21:37 , Processed in 0.409108 second(s), 16 queries , Gzip On, Redis On.

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表