Categories
Web Development

Truncate a Phrase Using Words, Not Characters (PHP)

Often when people truncate text in their WordPress excerpts or sample text, they simply limit the total number of characters and add an ellipsis. It’s pretty easy to do, but it usually ends up with a word being broken at the end.

For exampl…

This function will truncate any phrase by the number of words you specify and add an ellipsis if you specify one.

function ssm_truncate($phrase, $max_words, $ellipsis = '') {
   $phrase_array = explode(' ',$phrase);
   if(count($phrase_array) > $max_words && $max_words > 0)
      $phrase = implode(' ',array_slice($phrase_array, 0, $max_words)).$ellipsis;
   return $phrase;
}

One could expand on this and also add a character limit in the event that the phrase contains several long words. Perhaps I’ll do that someday.

By Tim Bunch

Tim Bunch is a Web Developer from Rockaway Beach, Oregon. As a web standards fanatic, he passionately pursues best practices. He also actively engages people on a wide range of topics in a variety of social media networks. Tim is also an avid Wordpress developer, music maker, coffee drinker, and child raiser. @timbunch

Leave a Reply