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';
}
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 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 :)
Top comments (3)
Prefer
stripos
if you need to check case insensitivephp.net/stripos
Nice. Thanks.
Is that searching for a distinct word or that sequence of characters? For instance, what would
if(Str::contains($string, 'rave'))
return?