Friday, September 17, 2010

php function to truncate string upto x characters

My sidebar now looks better now that I implement one of the codes I use on another project to truncate strings upto a certain chars, without cutting or truncating words

The Code

/**
* truncate_upto_chars
* @param string $string the string to truncate
* @param int $chars the number of characters, this will not "cut" words
* @param string $ellipsis the string to concatenate or put in the end of the string if truncated
* @see http://albertdiones.co.cc/blog/2010/09/php-function-to-truncate-string-upto-x.html
*/
function truncate_upto_chars($string,$chars,$ellipsis='…') {
  if (preg_match(sprintf('/^.{0,%u}(.*?\b|$)/',$chars),$string,$preg_matches)) {
    $str=$preg_matches[0];
    if (strlen($str)>=$chars)
      $str.=$ellipsis;
    return $str;
  }
  else
    ;#throw new Exception("failed to truncate $string");
}

I'm kinda amused to exceptions so I used them almost all the time. And I know not all are amused haha, that's why I commented it out

And I'm not really sure why I used sprintf there. You can edit it anyway if you like to use it. :)

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home