php中高性能中文字符串截取函数分享

这是用了phpwind里面的一个字符串截取函数,他支持gbk,gbk2312,utf-8等多种编码的字符截取,也很好高效的支持中文字符串的处理,代码如下:

  1. function substrs($content,$length,$add='Y'){
  2. if (strlen($content)>$length) {
  3. if ($GLOBALS['db_charset']!='utf-8') {
  4. $retstr = '';
  5. for ($i=0;$i<$length-2;$i++) {
  6. $retstr .= ord($content[$i]) > 127 ? $content[$i].$content[++$i] : $content[$i];
  7. }
  8. return $retstr.($add=='Y' ? ' ..' : '');
  9. }
  10. return utf8_trim(substr($content,0,$length)).($add=='Y' ? ' ..' : '');
  11. }
  12. return $content;
  13. }
  14. function utf8_trim($str) {
  15. $hex = '';
  16. $len = strlen($str)-1;
  17. for ($i=$len;$i>=0;$i-=1) {
  18. $ch = ord($str[$i]);
  19. $hex .= " $ch";
  20. if (($ch & 128)==0 || ($ch & 192)==192) {
  21. return substr($str,0,$i);
  22. }
  23. }
  24. return $str.$hex;
  25. }
  26. function cutstr($string, $length, $dot = ' ...') {
  27. global $charset;
  28. if(strlen($string) <= $length) {
  29. return $string;
  30. }
  31. $string = str_replace(array('&', '"', '<', '>'), array('&', '"', '<', '>'), $string);
  32. $strcut = '';
  33. if(strtolower($charset) == 'utf-8') {
  34. $n = $tn = $noc = 0;
  35. while($n < strlen($string)) {
  36. $t = ord($string[$n]);
  37. if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
  38. $tn = 1; $n++; $noc++;
  39. } elseif(194 <= $t && $t <= 223) {
  40. $tn = 2; $n += 2; $noc += 2;
  41. } elseif(224 <= $t && $t <= 239) {
  42. $tn = 3; $n += 3; $noc += 2;
  43. } elseif(240 <= $t && $t <= 247) {
  44. $tn = 4; $n += 4; $noc += 2;
  45. } elseif(248 <= $t && $t <= 251) {
  46. $tn = 5; $n += 5; $noc += 2;
  47. } elseif($t == 252 || $t == 253) {
  48. $tn = 6; $n += 6; $noc += 2;
  49. } else {
  50. $n++;
  51. }
  52. if($noc >= $length) {
  53. break;
  54. }
  55. }
  56. if($noc > $length) {
  57. $n -= $tn;
  58. }
  59. $strcut = substr($string, 0, $n);
  60. } else {
  61. for($i = 0; $i < $length; $i++) {
  62. $strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
  63. } //开源代码phpfensi.com
  64. }
  65. $strcut = str_replace(array('&', '"', '<', '>'), array('&', '"', '<', '>'), $strcut);
  66. return $strcut.$dot;
  67. }