Home > Backend Development > PHP Tutorial > PHP summary generation function (customized, no garbled code)

PHP summary generation function (customized, no garbled code)

WBOY
Release: 2016-07-25 09:04:09
Original
1008 people have browsed it
  1. /**
  2. php summary generation function
  3. link: http://bbs.it-home.org 2013-3-7
  4. */
  5. function cutstr($string, $length,$charset,$dot) {//Character, cut length, character set, end character
  6. if( strlen($string) <= $length) {
  7. return $string;
  8. }
  9. $pre = chr(1);
  10. $end = chr(1);
  11. //Protect special strings
  12. $string = str_replace( array('&', '"', '<', '>'), array($pre.'&'.$end, $pre.'"'.$end, $pre.'<' .$end, $pre.'>'.$end), $string);
  13. $strcut = '';
  14. if(strtolower($charset) == 'utf-8') {
  15. $n = $tn = $noc = 0;
  16. while($n < strlen($string)) {
  17. $t = ord($string[$n]);
  18. if($t == 9 || $t == 10 | | (32 <= $t && $t <= 126)) {
  19. $tn = 1; $n++; $noc++;
  20. } elseif(194 <= $t && $t <= 223) {
  21. $tn = 2; $n += 2; $noc += 2;
  22. } elseif(224 <= $t && $t <= 239) {
  23. $tn = 3; $n += 3; $noc += 2;
  24. } elseif(240 <= $t && $t <= 247) {
  25. $tn = 4; $n += 4; $noc += 2;
  26. } elseif(248 <= $ t && $t <= 251) {
  27. $tn = 5; $n += 5; $noc += 2;
  28. } elseif($t == 252 || $t == 253) {
  29. $tn = 6; $n += 6; $noc += 2;
  30. } else {
  31. $n++;
  32. }
  33. if($noc >= $length) {
  34. break;
  35. }
  36. }
  37. if($noc > $length) {
  38. $n -= $tn;
  39. }
  40. $strcut = substr($string, 0, $n);
  41. } else {
  42. for($i = 0; $i < $length; $i++ ) {
  43. $strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
  44. }
  45. }
  46. // Restore special string
  47. $strcut = str_replace(array($pre.'&'.$end, $pre.'"'.$end, $pre.'<'.$end, $pre.'>' .$end), array('&', '"', '<', '>'), $strcut);
  48. //Fix the problem of special string truncation
  49. $pos = strrpos($s , chr(1));
  50. if($pos !== false) {
  51. $strcut = substr($s,0,$pos);
  52. }
  53. return $strcut.$dot;
  54. }
  55. ?>
Copy code

The above is the complete code of the PHP summary generation function. You can copy it into your own editor and test it.



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