Laravel substrCount() function

In this tutorial, we will explain to you how to use laravel str substrCount() function with an example. The Str::substrCount method returns the number of occurrences of a given value in the given string:

for using string methods we need to load use Illuminate\Support\Str; in the file.

Below is a simple example to understand the same.

 $substrCount = Str::substrCount('i am learning from atcodex website','website');

 print_r($substrCount);

 // output - 1

In the above code, we can see we used substrCount method to check how many times the website has come in the sentence. Website words came only once a time in the sentence, so the result is 1. This method simply counts the occurrence of the string in the sentence.

Example

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\FileController;
use Illuminate\Support\Str;

class HomeController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        $substrCount1 = Str::substrCount('i like your bike, i like your car too', 'like');
        print_r($substrCount1);
        // output - 2

        $substrCount2 = Str::substrCount('my name is xyz, and and like it very much','much');
        print_r($substrCount2);
        // output - 1


    }
}

Output

2
1

Recommended Posts For You