How to Count the Number of Words in String in Laravel?

By Hardik Savani November 5, 2023 Category : Laravel

Hi Friends,

This article goes in detailed on laravel count words in string. We will look at an example of how to count number of words in a string in laravel. This example will help you how to count words in a string in laravel blade. you'll learn laravel Str::wordCount. Let's see below example laravel str wordcount() example.

Str::wordCount is not a built-in method in Laravel. It seems that you're trying to find the word count of a string using Laravel's Str class, but there is no such method available.

To count the number of words in a string, you can use plain PHP functions like str_word_count. Here's an example:

let's see the simple example:

Laravel String Count Number of Words in Controller

you can use it with controller like this way:

Controller Code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Illuminate\Support\Str;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index(Request $request)

{

$string = "Hello world! This is a string.";

$words = Str::wordCount($string);

dd($words);

}

}

Output:

6

Laravel String Count Number of Words in Blade File

you can use it with blade file like this way:

Blade File Code:

<p>{{ Str::wordCount("Hello world! This is a string.") }}</p>

Output:

6

I hope it can help you...

Tags :
Shares