Table of contents
 
                            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.
Read next

 
                        