Heim >Backend-Entwicklung >PHP-Tutorial >php不破坏单词截取子字符串

php不破坏单词截取子字符串

WBOY
WBOYOriginal
2016-07-25 08:43:08708Durchsuche

php不破坏单词截取子字符串

  1. /*
  2. snippet(phrase,[max length],[phrase tail])
  3. snippetgreedy(phrase,[max length before next space],[phrase tail])
  4. */
  5. function snippet($text,$length=64,$tail="...") {
  6. $text = trim($text);
  7. $txtl = strlen($text);
  8. if($txtl > $length) {
  9. for($i=1;$text[$length-$i]!=" ";$i++) {
  10. if($i == $length) {
  11. return substr($text,0,$length) . $tail;
  12. }
  13. }
  14. $text = substr($text,0,$length-$i+1) . $tail;
  15. }
  16. return $text;
  17. }
  18. // It behaves greedy, gets length characters ore goes for more
  19. function snippetgreedy($text,$length=64,$tail="...") {
  20. $text = trim($text);
  21. if(strlen($text) > $length) {
  22. for($i=0;$text[$length+$i]!=" ";$i++) {
  23. if(!$text[$length+$i]) {
  24. return $text;
  25. }
  26. }
  27. $text = substr($text,0,$length+$i) . $tail;
  28. }
  29. return $text;
  30. }
  31. // The same as the snippet but removing latest low punctuation chars,
  32. // if they exist (dots and commas). It performs a later suffixal trim of spaces
  33. function snippetwop($text,$length=64,$tail="...") {
  34. $text = trim($text);
  35. $txtl = strlen($text);
  36. if($txtl > $length) {
  37. for($i=1;$text[$length-$i]!=" ";$i++) {
  38. if($i == $length) {
  39. return substr($text,0,$length) . $tail;
  40. }
  41. }
  42. for(;$text[$length-$i]=="," || $text[$length-$i]=="." || $text[$length-$i]==" ";$i++) {;}
  43. $text = substr($text,0,$length-$i+1) . $tail;
  44. }
  45. return $text;
  46. }
  47. /*
  48. echo(snippet("this is not too long to run on the column on the left, perhaps, or perhaps yes, no idea") . "
    ");
  49. echo(snippetwop("this is not too long to run on the column on the left, perhaps, or perhaps yes, no idea") . "
    ");
  50. echo(snippetgreedy("this is not too long to run on the column on the left, perhaps, or perhaps yes, no idea"));
  51. */
复制代码

php


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn