Simplify String Checks in Laravel with doesntContain
Need to check if a string doesn’t contain certain words? Laravel’s new doesntContain
method for the Str
helper makes this task a breeze! Let's explore how this simple yet useful feature works.
Using doesntContain
The doesntContain
method is the opposite of contains
, returning true when a string doesn't include specific content:
use Illuminate\Support\Str;
$str = 'My favorite food is Pizza';
// Single value check
$result = Str::doesntContain($str, 'Steak'); // true
$result = Str::doesntContain($str, 'Pizza'); // false
Multiple Value Checks
You can also check multiple values at once:
$result = Str::doesntContain($str, ['Steak', 'Spaghetti']); // true
$result = Str::doesntContain($str, ['Steak', 'Spaghetti', 'Pizza']); // false
Real-World Example
Here’s how you might use it in a content filtering system:
class ContentFilter
{
protected array $bannedWords = ['spam', 'scam', 'free money'];
public function isClean(string $content): bool
{
return Str::doesntContain(
strtolower($content),
$this->bannedWords
);
}
public function filterComment(Comment $comment)
{
if ($this->isClean($comment->content)) {
$comment->approve();
} else {
$comment->markForReview();
}
}
}
The doesntContain
method provides a clean, intuitive way to check for the absence of strings in your content. Whether you're filtering content, validating input, or processing text, this method makes your code more readable and maintainable.
If this guide was helpful to you, subscribe to my daily newsletter and give me a follow on X/Twitter. It helps a lot!