We Recommend

Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems
Wicked Cool PHP contains a wide variety of scripts to process credit cards, check the validity of email addresses, template HTML, and serve dynamic images and text.


Posted By

melvitax on 03/03/08


Tagged

substr trim String shorten


Versions (?)


Who likes this?

6 people have marked this snippet as a favorite

adix
luman
revmitcz
jackShepler
pixelhandler
frara


Shorten text without braking words


Published in: PHP 


  1. /*
  2. returns text limited by a specified length of characters but keeping words intact. the final character count will not be exact since it is affected by the possible removing of the a long word or by the addition of the ellipsis.
  3.  
  4. paramaters:
  5. string - the input string
  6. chars - the length of characters wanted
  7. elli - the ellipsis to be used, defaults to '...'
  8. */
  9.  
  10. function shorten($string='', $chars=20, $elli='...'){
  11. list($new_string, $elli)= explode("\n", wordwrap($string, $chars, "\n", false));
  12. return ( $elli ) ? $new_string.'...' : $new_string;
  13. }

Report this snippet 

You need to login to post a comment.