Posted By

paulgrenwood on 09/23/09


Tagged

php truncate


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

digitalbart
nerdfiles


Truncate Text at Word Break


 / Published in: PHP
 

This function will truncate strings only at word breaks which can be used to show a teaser for complete article without breaking words.

  1. // Original PHP code by Chirp Internet: www.chirp.com.au
  2. // Please acknowledge use of this code by including this header.
  3. function myTruncate($string, $limit, $break=".", $pad="...") {
  4. // return with no change if string is shorter than $limit
  5. if(strlen($string) <= $limit)
  6. return $string;
  7.  
  8. // is $break present between $limit and the end of the string?
  9. if(false !== ($breakpoint = strpos($string, $break, $limit))) {
  10. if($breakpoint < strlen($string) - 1) {
  11. $string = substr($string, 0, $breakpoint) . $pad;
  12. }
  13. }
  14. return $string;
  15. }
  16. /***** Example ****/
  17. $short_string=myTruncate($long_string, 100, ' ');

Report this snippet  

You need to login to post a comment.