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

WBOY
发布: 2016-07-25 08:43:08
原创
689 人浏览过

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


来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板