当前位置:Gxlcms > PHP教程 > phpsubstr截断中文半个汉字乱码问题的解决方法

phpsubstr截断中文半个汉字乱码问题的解决方法

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

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

人气教程排行