Table of contents

check if string exists specific word in laravel

In this post, I will share how to check if the string contains a specific word in Laravel. Sometimes we need to check the submitted string if exists a particular word/string on it and Laravel provides an easy way how to do it.

 

In PHP if we want to do it. We need to use the strpos() function if the specific string exists on a string. The function below is before the PHP 8 version.

 

$a = 'This is laravel framework.';

if (strpos($a, 'laravel') !== false) {
    echo 'true';
}

 

But after the PHP 8 version, we can use str_contains() the function. See below on how to do it.

 

if (str_contains('How are you', 'are')) { 
    echo 'true';
}

 

Okay. What if we want to use the Laravel helper. So here is an example of how to use it.

use Illuminate\Support\Str;
   
$string = 'Laravel is the best PHP framework.';
     
if(Str::contains($string, 'framework')) {
   echo 'true';
}

 

For multiple words/strings, you can use an array for the second parameter as you can see below.

use Illuminate\Support\Str;
   
$string = 'Laravel is the best PHP framework.';
     
if(Str::contains($string, ['framework', 'php'])) {
   echo 'true';
}

 

I hope it helps. You can implement it in your controller.