PHP substring without breaking words


/ Published in: PHP
Save to your folder(s)



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

URL: http://us.php.net/substr

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.