欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

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

程序员文章站 2023-12-26 23:51:51
...
  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 $t = ord($string[$n]);
  16. if($t == 9 || $t == 10 || (32 $tn = 1;
  17. $n++;
  18. $noc++;
  19. } elseif(194 $tn = 2;
  20. $n += 2;
  21. $noc += 2;
  22. } elseif(224 $tn = 3;
  23. $n += 3;
  24. $noc += 2;
  25. } elseif(240 $tn = 4;
  26. $n += 4;
  27. $noc += 2;
  28. } elseif(248 $tn = 5;
  29. $n += 5;
  30. $noc += 2;
  31. } elseif($t == 252 || $t == 253) {
  32. $tn = 6;
  33. $n += 6;
  34. $noc += 2;
  35. } else {
  36. $n++;
  37. }
  38. if ($noc >= $length) {
  39. break;
  40. }
  41. }
  42. if ($noc > $length) {
  43. $n -= $tn;
  44. }
  45. $wordscut = substr($string, 0, $n);
  46. } else {
  47. for($i = 0; $i if(ord($string[$i]) > 127) {
  48. $wordscut .= $string[$i].$string[$i + 1];
  49. $i++;
  50. } else {
  51. $wordscut .= $string[$i];
  52. }
  53. }
  54. }
  55. $string = $wordscut;
  56. }
  57. return trim($string);
  58. }
  59. ?>
复制代码

上一篇:

下一篇: