Trim A String To A Given Word Count

Lots of times when you're theming a site, you'll want to have a snippet of text in one place or another.

Lots of times when you're theming a site, you'll want to have a snippet of text in one place or another. Drupal doesn't really have a good way of doing this because different languages have different definitions of "words", and a space-character is not always the delimiter between words, as it is in most Latin-based languages. But for those of us speaking languages that stick spaces between words, clients will often ask us to "just show the first 10 words" here or there. So here's a handy PHP function to do just that. And what's more, it can even add "…" at the end of the truncated text.

  

/**
 * Trim a string to a given number of words
 *
 * @param $string
 *   the original string
 * @param $count
 *   the word count
 * @param $ellipsis
 *   TRUE to add "..."
 *   or use a string to define other character
 * @param $node
 *   provide the node and we'll set the $node->
 *   
 * @return
 *   trimmed string with ellipsis added if it was truncated
 */
function word_trim($string, $count, $ellipsis = FALSE){
  $words = explode(' ', $string);
  if (count($words) > $count){
    array_splice($words, $count);
    $string = implode(' ', $words);
    if (is_string($ellipsis)){
      $string .= $ellipsis;
    }
    elseif ($ellipsis){
      $string .= '…';
    }
  }
  return $string;
}

?>

Get in touch with us

Tell us about your project or drop us a line. We'd love to hear from you!