Discovering the power of Str::contains() in Laravel

Understanding Str::contains()

The Str::contains() function in Laravel is a versatile tool for determining if a given substring exists within a string. Part of the Illuminate\Support\Str class, this method is especially useful for tasks involving string searching and validation.

Basic Usage

Here's a straightforward example to illustrate the basic usage of Str::contains():

use Illuminate\Support\Str;

$string = 'Laravel is an amazing PHP framework';

$containsLaravel = Str::contains($string, 'Laravel');
$containsSymfony = Str::contains($string, 'Symfony');

echo $containsLaravel ? 'Yes' : 'No'; // Output: Yes
echo $containsSymfony ? 'Yes' : 'No'; // Output: No

In this example, Str::contains() checks if the string contains the word 'Laravel' or 'Symfony'. The method returns true if the substring is found, and false otherwise.

Real-Life Example

Imagine you're developing a content management system (CMS) where you need to ensure that certain keywords are present in the content before publishing. Here’s how Str::contains() can help:

use Illuminate\Support\Str;

$content = 'This blog post discusses the various features of Laravel and how it simplifies web development.';

$keywords = ['Laravel', 'PHP', 'framework'];

foreach ($keywords as $keyword) {
    if (Str::contains($content, $keyword)) {
        echo "The content contains the keyword: $keyword\n";
    } else {
        echo "The content does not contain the keyword: $keyword\n";
    }
}

// Output:
// The content contains the keyword: Laravel
// The content contains the keyword: PHP
// The content contains the keyword: framework

In this example, Str::contains() is used to check if each keyword exists within the content string. This ensures that your content includes all necessary keywords before it's published.

Conclusion

The Str::contains() function in Laravel is a powerful and efficient way to search for substrings within a string. Whether you’re validating content, searching for keywords, or simply checking for the presence of a substring, Str::contains() makes the task easy and intuitive.

Found this helpful?

If this guide was helpful to you, subscribe to my daily newsletter and give me a follow on X/Twitter. It helps a lot!

Subscribe to Harris Raftopoulos

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe