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
Approach 1: Using str_word_count() Method: The str_word_count() method is used to counts the number of words in a string.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With