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

來源:互聯網
上載者:User
  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. }

複製代碼
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.