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

PHP实现截取字符串的通用方法

程序员文章站 2022-04-09 23:41:34
...
  1. /**
  2. * 截取字符串
  3. * params $string 要截取的字符串
  4. * params $length: 保留长度(字符数)
  5. * params $dot: 多余部分显示
  6. **/
  7. function _cutstr($string, $length, $dot = ' ...') {
  8. if(strlen($string) return $string;
  9. }
  10. $string = str_replace(array('&', '"', ''), array('&', '"', ''), $string);
  11. $strcut = '';
  12. $n = $tn = $noc = 0;
  13. while($n $t = ord($string[$n]);
  14. if($t == 9 || $t == 10 || (32 $tn = 1; $n++; $noc++;
  15. } elseif(194 $tn = 2; $n += 2; $noc += 2;
  16. } elseif(224 $tn = 3; $n += 3; $noc += 2;
  17. } elseif(240 $tn = 4; $n += 4; $noc += 2;
  18. } elseif(248 $tn = 5; $n += 5; $noc += 2;
  19. } elseif($t == 252 || $t == 253) {
  20. $tn = 6; $n += 6; $noc += 2;
  21. } else {
  22. $n++;
  23. }
  24. if($noc >= $length) {
  25. break;
  26. }
  27. }
  28. if($noc > $length) {
  29. $n -= $tn;
  30. }
  31. $strcut = substr($string, 0, $n);
  32. $strcut = str_replace(array('&', '"', ''), array('&', '"', ''), $strcut);
  33. return $strcut.$dot;
  34. }
复制代码

PHP