Home  >  Article  >  Backend Development  >  PHP implements a general method for intercepting strings

PHP implements a general method for intercepting strings

WBOY
WBOYOriginal
2016-07-25 08:45:30955browse
  1. /**
  2. * Intercept string
  3. * params $string The string to be intercepted
  4. * params $length: reserved length (number of characters)
  5. * params $dot: display the excess part
  6. **/
  7. function _cutstr($string, $length, $dot = ' ...') {
  8. if(strlen($string) <= $length) {
  9. return $string;
  10. }
  11. $string = str_replace(array('&', '"', '<', '>'), array('&', '"', '<', '>'), $string);
  12. $strcut = '';
  13. $n = $tn = $noc = 0;
  14. while($n < strlen($string)) {
  15. $t = ord($string[$n]);
  16. if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
  17. $tn = 1; $n++; $noc++;
  18. } elseif(194 <= $t && $t <= 223) {
  19. $tn = 2; $n += 2; $noc += 2;
  20. } elseif(224 <= $t && $t < 239) {
  21. $tn = 3; $n += 3; $noc += 2;
  22. } elseif(240 <= $t && $t <= 247) {
  23. $tn = 4; $n += 4; $noc += 2;
  24. } elseif(248 <= $t && $t <= 251) {
  25. $tn = 5; $n += 5; $noc += 2;
  26. } elseif($t == 252 || $t == 253) {
  27. $tn = 6; $n += 6; $noc += 2;
  28. } else {
  29. $n++;
  30. }
  31. if($noc >= $length) {
  32. break;
  33. }
  34. }
  35. if($noc > $length) {
  36. $n -= $tn;
  37. }
  38. $strcut = substr($string, 0, $n);
  39. $strcut = str_replace(array('&', '"', '<', '>'), array('&', '"', '<', '>'), $strcut);
  40. return $strcut.$dot;
  41. }
复制代码

PHP


Statement:
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