Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 926
JasonBartholme Avatar asked Jul 11 '09 04:07

JasonBartholme


People also ask

Which PHP string function counts the number of words in a string?

Approach 1: Using str_word_count() Method: The str_word_count() method is used to counts the number of words in a string.

How do I count the number of letters in a string in PHP?

You can simply use the PHP strlen() function to find the number of characters in a string of text. It also includes the white spaces inside the specified string.


2 Answers

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.

like image 123
jason Avatar answered Nov 15 '22 23:11

jason


str_word_count takes an optional parameter that tells it what to return.

Returns an array of strings that are the words:

$words = str_word_count($var, 1);

Then you can slice things up with something like:

$len = min(50, count($words));
$first_fifty = array_slice($words, 0, $len);
like image 43
geofflane Avatar answered Nov 15 '22 22:11

geofflane