首页 >后端开发 >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 $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. ?>
复制代码


声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn