How to count the number of words in a string in Laravel

Overview

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.

What is the 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.

Syntax

Str::of('Hello, world!')->wordCount(); // 2

Parameters

The wordCount() does not receive any parameters.

Example

use Illuminate\Support\Str;

public function countWords(){
Str::of('People with big heads are very intelligent')->wordCount(); // 7;
echo $string;
}

Explanation

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.

Free Resources