首頁 >後端開發 >php教程 >php截取utf8或gbk編碼中英文字串

php截取utf8或gbk編碼中英文字串

WBOY
WBOY原創
2016-07-25 08:53:51923瀏覽
  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. }

复制代码


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:php是什麼文件下一篇:php是什麼文件