Truncate Text at Word Break


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

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


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.