Counting Word Occurrences
Learn how to count the occurrences of a word in a string with the help of examples.
Implementation of the wordCount
helper method
While Laravel already provides a wordCount
helper method, we could also use our wordSplit
method in combination with PHP’s count
function:
Press + to interact
<?phpuse Illuminate\Support\Str;$string = 'The quick brown fox jumps over the lazy dog.';// Returns 9count(Str::wordSplit($string));// Returns 9Str::wordCount($string);
While using our custom method this way is not particularly advantageous, we can use it to accomplish some more nuanced tasks. One such thing might be to count the number of unique words in a string:
Press + to interact
<?phpuse Illuminate\Support\Str;// Returns 9count(array_unique(Str::wordSplit($string)));
The example in the code above doesn’t seem to be working quite right because it returns the same number of words as before. The ...