Home > Backend Development > PHP Tutorial > Solution to the problem of php substr truncating half of Chinese characters into garbled characters

Solution to the problem of php substr truncating half of Chinese characters into garbled characters

WBOY
Release: 2016-07-25 08:58:42
Original
1300 people have browsed it
  1. /**
  2. * Improved 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. ?>
复制代码


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template