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
<?php
use Illuminate\Support\Str;
$string = 'The quick brown fox jumps over the lazy dog.';
// Returns 9
count(Str::wordSplit($string));
// Returns 9
Str::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
<?php
use Illuminate\Support\Str;
// Returns 9
count(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 ...