How to Count the Number of Words in String in Laravel

  Oct 2023
  ITSolutionsGuides
  Category: Laravel
How to Count the Number of Words in String in Laravel

Hi Developers,

Today lets learn how to count the number of words in the string in both frontend and backend for performing calculations in frontend and to analyse any incoming data from the user to the database, Lets see how both the method is done.

In Controller File

In some cases we need to count the number of words submitted by the user to avoid overload while storing the data in the database.

To avoid this issue we need to analysis the input string before adding,

Lets see how to count the number of words in a string using the Str::wordCount function in Laravel Controller

<?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 test string by ITSolutionsGuides.";

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

  

        dd($words);

    }

}

In Blade File

Sometime we need to count the number of words in the frontend for better execution speed. To achieve that we need to use the function in the blade file inside the double curly braces.

Lets see how to count the number of words in a string using the Str::wordCount function in Laravel Blade file.

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

We hope it helps everyone. Thanks for supporting ITSolutionsGuides and keep supporting us also follow us in social media platforms.

Subscribe for NewsLetter

Be the first to know about releases and tutorial news and solutions.

We care about your data in our privacy policy.

ITSolutionsGuides

ITSolutionsGuides was started mainly to provide good and quality web solutions for all the developers. We provide tutorials to support all the developers and also we try to provide solutions to the errors we face while coding.

Contact US

ITSolutionsGuides, provide users with an easy-to-use form to reach out for support or inquiries.

whatsapp  gmail  instagram-new--v1  facebook-circled  twitter-circled  linkedin  github  pinterest 

Copyright © 2023 - 2024 All rights reserved | ITSolutionsGuides