Home  >  Article  >  Backend Development  >  PHP intercepts UTF8 or GBK encoded Chinese and English strings

PHP intercepts UTF8 or GBK encoded Chinese and English strings

WBOY
WBOYOriginal
2016-07-25 08:53:51847browse
  1. //String interception

  2. $a = "s@@Hello";
  3. var_dump(strlen_weibo($a,'utf-8'));
  4. Result The output is 8, in which the letter s counts as 1, the full-width @ counts as 2, the half-width @ counts as 1, and the two Chinese characters count as 4. The source code is as follows:

  5. //Function code to intercept strings

  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. }

Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What file is phpNext article:What file is php