HOWTO: Quickly Truncate a Block of Text

When theming things I run into situations where a block of text is too long and I need a really quick way to truncate text and append an ellipses or custom trailing text. The built in drupal teaser truncates text in a much more logical manner (watches out for html tags and the like) while this php snippet is simpler and meant to run on pure text. You can do strip_tags() if you want to remove all the html tags before running this code on your piece of text. I often just drop this into my template.php and use it in various spots in the theme.

 

/**
* Truncate the string if it is beyond a certain $length and append with an ellipses or custom text
* $length is the number of characters allowed before truncating
* $append is appended to the truncated string
*/

function your_theme_custom_truncate($string = '', $length = 30, $append = '…') {
  return
strlen($string) > $length ? trim(substr($string, 0, $length)) . $append : $string;
}

?>

 

Before:

Suspendisse potenti. Ut tempus auctor libero. Aliquam molestie dolor quis lectus. Curabitur et erat eget lorem nonummy ultrices. Mauris interdum. Etiam imperdiet viverra purus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris sem mauris, feugiat at, dictum vitae, placerat nec, odio. Nulla fringilla. Morbi justo nulla, commodo quis, ultricies a, eleifend eu, ante. Morbi eget erat eu ante tincidunt interdum. Nullam at est. Nulla ultrices pede vitae sapien bibendum bibendum. Quisque turpis enim, ullamcorper at, fermentum quis, vulputate quis, libero. In facilisis, dui eget accumsan molestie, justo metus tempor quam, eu tempor ipsum eros a urna. Donec aliquet. Curabitur condimentum volutpat augue. Praesent bibendum commodo enim.

After:

Suspendisse potenti. Ut tempus auctor libero. Aliquam molestie dolor quis lectus. Curabitur
et erat eget lorem nonummy ul…