Posted By

tcmacdonald on 02/06/10


Tagged

php String truncate


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

Onfire60


Truncate a string


 / Published in: PHP
 

  1. /**
  2.  * Truncate a string to a certain length if necessary,
  3.  * optionally splitting in the middle of a word, and
  4.  * appending the $etc string or inserting $etc into the middle.
  5.  * @param string
  6.  * @param integer
  7.  * @param string
  8.  * @param boolean
  9.  * @param boolean
  10.  * @return string
  11.  */
  12. function truncate($string, $length = 80, $etc = '...',$break_words = false, $middle = false) {
  13. if ($length == 0)
  14. return '';
  15. if (strlen($string) > $length) {
  16. $length -= min($length, strlen($etc));
  17. if (!$break_words && !$middle) {
  18. $string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length+1));
  19. }
  20. if(!$middle) {
  21. return substr($string, 0, $length) . $etc;
  22. } else {
  23. return substr($string, 0, $length/2) . $etc . substr($string, -$length/2);
  24. }
  25. } else {
  26. return $string;
  27. }
  28. }

Report this snippet  

You need to login to post a comment.