Php intercepts UTF-8 or gbk encoded Chinese and English strings

Source: Internet
Author: User
Php intercepts UTF-8 or gbk encoded Chinese and English strings

  1. // String truncation

  2. $ A = "s @ ";
  3. Var_dump (strlen_weibo ($ a, 'utf-8 '));
  4. The result output is 8, where the letter s is counted as 1, the full @ count is 2, the half @ count is 1, and the two Chinese counts are 4. The source code is as follows:

  5. // Extract the function code of the string

  6. Function strlen_weibo ($ string, $ charset = 'utf-8 ')
  7. {
  8. $ N = $ count = 0;
  9. $ Length = strlen ($ string );
  10. If (strtolower ($ charset) = 'utf-8 ')
  11. {
  12. While ($ n <$ length)
  13. {
  14. $ CurrentByte = ord ($ string [$ n]);
  15. If ($ currentByte = 9 |
  16. $ CurrentByte = 10 |
  17. (32 <=$ currentByte & $ currentByte <= 126) // bbs.it-home.org
  18. {
  19. $ N ++;
  20. $ Count ++;
  21. } Elseif (194 <=$ currentByte & $ currentByte <= 223)
  22. {
  23. $ N + = 2;
  24. $ Count + = 2;
  25. } Elseif (224 <=$ currentByte & $ currentByte <= 239)
  26. {
  27. $ N + = 3;
  28. $ Count + = 2;
  29. } Elseif (240 <=$ currentByte & $ currentByte <= 247)
  30. {
  31. $ N + = 4;
  32. $ Count + = 2;
  33. } Elseif (248 <=$ currentByte & $ currentByte <= 251)
  34. {
  35. $ N + = 5;
  36. $ Count + = 2;
  37. } Elseif ($ currentByte = 252 | $ currentByte = 253)
  38. {
  39. $ N + = 6;
  40. $ Count + = 2;
  41. } Else
  42. {
  43. $ N ++;
  44. $ Count ++;
  45. }
  46. If ($ count> = $ length)
  47. {
  48. Break;
  49. }
  50. }
  51. Return $ count;
  52. } Else
  53. {
  54. For ($ I = 0; $ I <$ length; $ I ++)
  55. {
  56. If (ord ($ string [$ I])> 127)
  57. {
  58. $ I ++;
  59. $ Count ++;
  60. }
  61. $ Count ++;
  62. }
  63. Return $ count;
  64. }
  65. }

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.