DEV Community

Cover image for How To Check if String Contains Specific Word in PHP Laravel
codeanddeploy
codeanddeploy

Posted on

How To Check if String Contains Specific Word in PHP Laravel

Originally posted @ https://codeanddeploy.com visit and download the sample code:
https://codeanddeploy.com/blog/laravel/how-to-check-if-string-contains-specific-word-in-php-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';
}
Enter fullscreen mode Exit fullscreen mode

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';
}
Enter fullscreen mode Exit fullscreen mode

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';
}
Enter fullscreen mode Exit fullscreen mode

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';
}
Enter fullscreen mode Exit fullscreen mode

I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/laravel/how-to-check-if-string-contains-specific-word-in-php-laravel if you want to download this code.

Happy coding :)

Discussion (3)

Collapse
damosse31 profile image
Damien M

Prefer stripos if you need to check case insensitive

php.net/stripos

Collapse
codeanddeploy profile image
codeanddeploy Author

Nice. Thanks.

Collapse
moopet profile image
Ben Sinclair

Is that searching for a distinct word or that sequence of characters? For instance, what would if(Str::contains($string, 'rave')) return?