首頁 >後端開發 >php教程 >php substr截斷中文半個漢字亂碼問題的解法

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

WBOY
WBOY原創
2016-07-25 08:58:421271瀏覽
  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. ?>
复制代码


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