I would recommend against using the number of words as a baseline. You could easily end up with much less or much more data than you intended to display.
One approach I've used in the past is to ask for a desired length, but make sure it does not truncate a word. Here's something that may work for you:
function function_that_shortens_text_but_doesnt_cutoff_words($text, $length)
{
if(strlen($text) > $length) {
$text = substr($text, 0, strpos($text, ' ', $length));
}
return $text;
}
That said, if you pass 1
as the second parameter to str_word_count
, it will return an array containing all the words, and you can use array manipulation on that.
Also, you could although, it's somewhat hackey, explode the string on spaces, etc... But that introduces lots of room for error, such as things that are not words getting counted as words.
PS. If you need a Unicode safe version of the above function, and have either the mbstring
or iconv
extensions installed, simply replace all the string functions with their mb_
or iconv_
prefixed equivalents.