首頁 >後端開發 >php教程 >php不破壞單字截取子字串

php不破壞單字截取子字串

WBOY
WBOY原創
2016-07-25 08:43:08707瀏覽

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


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn