当前位置:Gxlcms > PHP教程 > php截取utf8或gbk编码中英文字符串

php截取utf8或gbk编码中英文字符串

时间:2021-07-01 10:21:17 帮助过:22人阅读

  1. //字符串截取

  2. $a = "s@@你好";
  3. var_dump(strlen_weibo($a,'utf-8'));
  4. 结果输出为8,其中字母s计数为1,全角@计数为2,半角@计数为1,两个中文计数为4。源码如下:

  5. //截取字符串的函数代码

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

人气教程排行