[PHP实例] php不破坏单词截取子字符串

来源:互联网 发布:hadoop spark hive知乎 编辑:程序博客网 时间:2024/05/01 21:27

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

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