php汉字转码Unicode编码函数

WBOY
Freigeben: 2016-07-25 08:53:48
Original
3618 Leute haben es durchsucht
  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 $dec = hexdec(bin2hex($arrstr[$i]));
  12. $unistr .= $prefix . $dec . $postfix;
  13. }
  14. return $unistr;
  15. } // 脚本学堂 bbs.it-home.org
  16. /**
  17. * $str Unicode编码后的字符串
  18. * $encoding 原始字符串的编码,默认GBK
  19. * $prefix 编码字符串的前缀,默认""
  20. * $postfix 编码字符串的后缀,默认";"
  21. */
  22. function unicode_decode($unistr, $encoding = 'GBK', $prefix = '', $postfix = ';') {
  23. $arruni = explode($prefix, $unistr);
  24. $unistr = '';
  25. for($i = 1, $len = count($arruni); $i if (strlen($postfix) > 0) {
  26. $arruni[$i] = substr($arruni[$i], 0, strlen($arruni[$i]) - strlen($postfix));
  27. }
  28. $temp = intval($arruni[$i]);
  29. $unistr .= ($temp }
  30. return iconv('UCS-2', $encoding, $unistr);
  31. }
复制代码

例子,php汉字转换函数的范例,实现编码转换:

  1. //GBK字符串测试
  2. $str = '哈哈';
  3. echo $str.'
    ';
  4. $unistr = unicode_encode($str);
  5. echo $unistr.'
    '; // 哈哈
  6. $str2 = unicode_decode($unistr);
  7. echo $str2.'
    '; //哈哈
  8. //UTF-8字符串测试
  9. $utf8_str = iconv('GBK', 'UTF-8', $str);
  10. echo $utf8_str.'
    '; // 鍝堝搱 注:UTF在GBK下显示的乱码!可切换浏览器的编码测试
  11. $utf8_unistr = unicode_encode($utf8_str, 'UTF-8');
  12. echo $utf8_unistr.'
    '; // 哈哈
  13. $utf8_str2 = unicode_decode($utf8_unistr, 'UTF-8');
  14. echo $utf8_str2.'
    '; // 鍝堝搱
  15. //其它后缀、前缀测试
  16. $prefix_unistr = unicode_encode($str, 'GBK', "\\u", '');
  17. echo $prefix_unistr.'
    '; // \u60\u98\u62\u21704\u21704\u60\u47\u98\u62
  18. $profix_unistr2 = unicode_decode($prefix_unistr, 'GBK', "\\u", '');
  19. echo $profix_unistr2.'
    '; //哈哈
复制代码


Verwandte Etiketten:
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!