A UTF-8 encoded Unicode function implemented by php

Source: Internet
Author: User
Tags 0xc0
A UTF-8 encoded Unicode function implemented by php

  1. Function Utf8ToUnicode (strUtf8)

  2. {
  3. Var bstr = "";
  4. Var nTotalChars = strUtf8.length; // total chars to be processed.
  5. Var nOffset = 0; // processing point on strUtf8
  6. Var nRemainingBytes = nTotalChars; // how many bytes left to be converted
  7. Var nOutputPosition = 0;
  8. Var iCode, iCode1, iCode2; // the value of the unicode.

  9. While (nOffset <nTotalChars)

  10. {
  11. ICode = strUtf8.charCodeAt (nOffset );
  12. If (iCode & 0x80) = 0) // 1 byte.
  13. {
  14. If (nRemainingBytes <1) // not enough data
  15. Break;

  16. Bstr + = String. fromCharCode (iCode & 0 × 7F );

  17. NOffset ++;
  18. NRemainingBytes-= 1;
  19. }
  20. Else if (iCode & 0xE0) = 0xC0) // 2 bytes
  21. {
  22. ICode1 = strUtf8.charCodeAt (nOffset + 1 );
  23. If (nRemainingBytes <2 | // not enough data
  24. (ICode1 & 0xC0 )! = 0 × 80) // invalid pattern
  25. {
  26. Break;
  27. }

  28. Bstr + = String. fromCharCode (iCode & 0 × 3F) <6) | (iCode1 & 0 × 3F ));

  29. NOffset + = 2;
  30. NRemainingBytes-= 2;
  31. }
  32. Else if (iCode & 0xF0) = 0xE0) // 3 bytes
  33. {
  34. ICode1 = strUtf8.charCodeAt (nOffset + 1 );
  35. ICode2 = strUtf8.charCodeAt (nOffset + 2 );
  36. If (nRemainingBytes <3 | // not enough data
  37. (ICode1 & 0xC0 )! = 0 × 80 | // invalid pattern
  38. (ICode2 & 0xC0 )! = 0 × 80)
  39. {
  40. Break;
  41. }

  42. Bstr + = String. fromCharCode (iCode & 0 × 0F) <12) |

  43. (ICode1 & 0 × 3F) <6) |
  44. (ICode2 & 0 × 3F ));
  45. NOffset + = 3;
  46. NRemainingBytes-= 3;
  47. }
  48. Else // 4 or more bytes-unsupported
  49. Break;
  50. }

  51. If (nRemainingBytes! = 0)

  52. {
  53. // Bad UTF8 string.
  54. Return "";
  55. }

  56. Return bstr;

  57. }
  58. ?>

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.