If you create an editorial application or a site that deals with essays and write-ups, you will probably need to count the number of words. There can be limitations to the number of words, so instead of getting the text and manually counting the words, you can use the wordCount()
method in Laravel.
wordCount()
method?The wordCount()
method is one of many methods Laravel uses to manipulate strings. The wordCount()
method counts the number of words in a string.
Str::of('Hello, world!')->wordCount(); // 2
The wordCount()
does not receive any parameters.
use Illuminate\Support\Str;
public function countWords(){
Str::of('People with big heads are very intelligent')->wordCount(); // 7;
echo $string;
}
In the example above, we import the use Illuminate\Support\Str;
class and create a countWords()
function in our controller; you can do this in an existing controller.
The countWords()
function uses the Str
facade, which is a Laravel facade for working with strings. We then call the of()
method, which is a fluent and objectified way to manipulate strings and chain other string operations in Laravel.
We pass the whole string we want to count into the of()
method. We then chain the wordCount()
method to count the words passed into the of()
method.