How do I get only a determined number of words from a string in php?

function, php, string

Solution

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.

Problem

Here is what I am trying to do. I have a block of text and I would like to extract the first 50 words from the string without cutting off the words in the middle. That is why I would prefer words opposed to characters, then I could just use a left() function. I know the str_word_count($var) function will return the number of words in a string, but how would I return only the first 50 words? I'm going full immersion on PHP and I'm not familiar with many of the string functions, yet. Thanks in advance, Jason

Original source