Search⌘ K
AI Features

Counting Word Occurrences

Explore how to use Laravel's string helper methods and collections to count word occurrences in text. Understand case normalization and unique word handling to refine string analysis within PHP applications.

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:

PHP
<?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:

PHP
<?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 culprit is the ...