php substr截斷中文半個漢字亂碼問題的解決方案

來源:互聯網
上載者:User
  1. /**
  2. * 改進的substr
  3. * edit bbs.it-home.org
  4. */
  5. function getstr($string, $length, $encoding = 'utf-8') {
  6. $string = trim($string);
  7. if($length && strlen($string) > $length) {
  8. //截斷字元
  9. $wordscut = '';
  10. if(strtolower($encoding) == 'utf-8') {
  11. //utf8編碼
  12. $n = 0;
  13. $tn = 0;
  14. $noc = 0;
  15. while ($n < strlen($string)) {
  16. $t = ord($string[$n]);
  17. if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
  18. $tn = 1;
  19. $n++;
  20. $noc++;
  21. } elseif(194 <= $t && $t <= 223) {
  22. $tn = 2;
  23. $n += 2;
  24. $noc += 2;
  25. } elseif(224 <= $t && $t < 239) {
  26. $tn = 3;
  27. $n += 3;
  28. $noc += 2;
  29. } elseif(240 <= $t && $t <= 247) {
  30. $tn = 4;
  31. $n += 4;
  32. $noc += 2;
  33. } elseif(248 <= $t && $t <= 251) {
  34. $tn = 5;
  35. $n += 5;
  36. $noc += 2;
  37. } elseif($t == 252 || $t == 253) {
  38. $tn = 6;
  39. $n += 6;
  40. $noc += 2;
  41. } else {
  42. $n++;
  43. }
  44. if ($noc >= $length) {
  45. break;
  46. }
  47. }
  48. if ($noc > $length) {
  49. $n -= $tn;
  50. }
  51. $wordscut = substr($string, 0, $n);
  52. } else {
  53. for($i = 0; $i < $length - 1; $i++) {
  54. if(ord($string[$i]) > 127) {
  55. $wordscut .= $string[$i].$string[$i + 1];
  56. $i++;
  57. } else {
  58. $wordscut .= $string[$i];
  59. }
  60. }
  61. }
  62. $string = $wordscut;
  63. }
  64. return trim($string);
  65. }
  66. ?>
複製代碼
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.