How to Check if a String Contains a Specific Word in Laravel

- Andrés Cruz

En español

Many times we want to know how we can search for a text within another text in Laravel, that is, we want to know if a text is contained within another text in Laravel; In PHP, we have the str_contains method:

if (str_contains("Text Large", "Large")) {
    echo 'The string "Large" was found in the string';
} else {
    echo '"Large" was not found because the case does not match';
}

Although in Laravel, as you already know, we have a specific kit of helpers to use for texts in a simpler way in the Laravel style; let's remember that we have two ways, using Facades:

$contains = Str::contains("Text Large", "Large");

The above code returns True, since the text "Large" is contained within "Text Large"

The most recommended way is to use the help functions:

$contains = str("Text Large")->contains("Large");

To use any of the string helper methods, we first have to create the wrapper and that is what the str() function is for, from there, we can use any of the helper methods such as contains() which works in the same way as its Facade version.

Multiple Word Verification

We can also check if the String contains multiple words or substrings. For example:

$contains = Str::contains($myString, ['desarrollolibre.net', 'other text']);

You can use these methods that allow you to verify if the string contains a specific word in Laravel 6, Laravel 7, Laravel 8, Laravel 9, Laravel 10 and Laravel 11.

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.