Php Chinese character unicode encoding and decoding

Source: Internet
Author: User
Php Chinese character unicode encoding and decoding

  1. // Encode the content in unicode format: yoka \ u738b (original: yoka King)

  2. Function unicode_encode ($ name)
  3. {
  4. $ Name = iconv ('utf-8', 'ucs-2', $ name );
  5. $ Len = strlen ($ name );
  6. $ Str = '';
  7. For ($ I = 0; $ I <$ len-1; $ I = $ I + 2)
  8. {
  9. $ C = $ name [$ I];
  10. $ C2 = $ name [$ I + 1];
  11. If (ord ($ c)> 0)
  12. {// Two-byte text
  13. $ Str. = '\ U'. base_convert (ord ($ c), 10, 16). base_convert (ord ($ c2), 10, 16 );
  14. }
  15. Else
  16. {
  17. $ Str. = $ c2;
  18. }
  19. }
  20. Return $ str;
  21. } // (Script School bbs.it-home.org editing)

  22. // Decodes the unicode encoded content. the encoded content format is yoka \ u738b (original: yoka King)

  23. Function unicode_decode ($ name)
  24. {
  25. // Convert the unicode encoding to the UTF-8 encoding that can be viewed
  26. $ Pattern = '/([\ w] +) | (\ u ([\ w] {4})/I ';
  27. Preg_match_all ($ pattern, $ name, $ matches );
  28. If (! Empty ($ matches ))
  29. {
  30. $ Name = '';
  31. For ($ j = 0; $ j <count ($ matches [0]); $ j ++)
  32. {
  33. $ Str = $ matches [0] [$ j];
  34. If (strpos ($ str, '\ u') = 0)
  35. {
  36. $ Code = base_convert (substr ($ str, 2, 2), 16, 10 );
  37. $ Code2 = base_convert (substr ($ str, 4), 16, 10 );
  38. $ C = chr ($ code). chr ($ code2 );
  39. $ C = iconv ('ucs-2', 'utf-8', $ c );
  40. $ Name. = $ c;
  41. }
  42. Else
  43. {
  44. $ Name. = $ str;
  45. }
  46. }
  47. }
  48. Return $ name;
  49. }

Test:

  1. Echo 'yoka \ u738b-> '. unicode_decode ('yoka \ u738b ').'';
  2. $ Name = 'yoka King ';
  3. Echo ''. unicode_encode ($ name ).'';

Note: The Sina blog editor filters out /***/.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.