Truncate text at word break


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



Copy this code and paste it in your HTML
  1. function myTruncate($string, $limit, $break=".", $pad="...") {
  2. // return with no change if string is shorter than $limit
  3. if(strlen($string) <= $limit)
  4. return $string;
  5.  
  6. // is $break present between $limit and the end of the string?
  7. if(false !== ($breakpoint = strpos($string, $break, $limit))) {
  8. if($breakpoint < strlen($string) - 1) {
  9. $string = substr($string, 0, $breakpoint) . $pad;
  10. }
  11. }
  12. return $string;
  13. }
  14. /***** Example ****/
  15. $short_string=myTruncate($long_string, 100, ' ');

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.