Home > Backend Development > PHP Tutorial > Checking String Absence with Laravel's doesntContain

Checking String Absence with Laravel's doesntContain

Karen Carpenter
Release: 2025-03-10 11:12:09
Original
744 people have browsed it

Checking String Absence with Laravel's doesntContain

Laravel's doesntContain method provides a more intuitive way to check if a string is missing something. This method complements the existing contains method and provides a cleaner syntax for negative checking.

use Illuminate\Support\Str;

// 基本用法
$text = "Welcome to Laravel";
$result = Str::doesntContain($text, 'PHP'); // true
// 多重检查
$result = Str::doesntContain($text, ['PHP', 'Laravel']); // false
Copy after login

The following is an actual example of implementing a message filtering service:

<?php namespace App\Services;

use App\Models\Message;
use Illuminate\Support\Str;

class MessageFilter
{
    protected array $sensitiveTerms = [
        'confidential',
        'internal',
        'classified'
    ];

    public function isSafeForPublic(Message $message): bool
    {
        return Str::doesntContain(
            strtolower($message->content),
            $this->sensitiveTerms
        );
    }

    public function processMessage(Message $message): array
    {
        if ($this->isSafeForPublic($message)) {
            $message->update(['status' => 'published']);
            return ['status' => 'success', 'message' => 'Message published'];
        }
        $message->update(['status' => 'review_required']);

        return ['status' => 'pending', 'message' => 'Content needs review'];
    }
}
Copy after login
The

doesntContain method simplifies string validation in Laravel applications, providing a more intuitive syntax to check for the absence of specific content. Whether you are building a content audit system, input verification, or data filtering, this approach reduces complexity and improves code readability. Combined with other string helper functions of Laravel, it forms a comprehensive toolkit for efficient string manipulation.

The above is the detailed content of Checking String Absence with Laravel's doesntContain. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template