PHP Laravel How do I check if a string contains a specific word?

Today, We are going to learn how to check if a string contains a specific word or not. We can check easily using a single line of code in Laravel and PHP. Laravel provides a simple string library and PHP provides a simple strpos function for check if a string contains a specific word or not.

PHP Laravel How do I check if a string contains a specific word?

We are going to use Laravel string library. Laravel string library provides a contains function. This function is useful to find the specific word form string. using this function we able to find the multiple words from the string. Let's see the example step by step.

Laravel find a single word from the string

//Load support library
use Illuminate\Support\Str;
$string = 'LaravelHive provide laravel example and tutorial step by step';
$result = Str::contains($string, 'tutorial');
if( $result ){
print "Found the word!";
}else{
print "Word not found!";
}

Laravel find multiple words from the string

//Load support library
use Illuminate\Support\Str;
$string = 'LaravelHive provide laravel example and tutorial step by step';
$result = Str::contains($string, ['example','tutorial']);
if( $result ){
print "Found the word!";
}else{
print "Word not found!";
}

It will check for both words return true if found both words from the string.

PHP find a word from the string

Now, We are going to see how we can find a specific word from string using PHP

$string = 'LaravelHive provide laravel example and tutorial step by step';
if( strpos($string, 'tutorial') !== false ){
print "Found the word!";
}else{
print "Word not found!";
}

Also, Using PHP we can easily find a word from the string. I hope this tutorial is helpful to you.

Tags:

Related Posts: