首頁 > 後端開發 > php教程 > 使用Laravel' d dorntcontain檢查字符串缺失

使用Laravel' d dorntcontain檢查字符串缺失

Karen Carpenter
發布: 2025-03-10 11:12:09
原創
745 人瀏覽過

Checking String Absence with Laravel's doesntContain

Laravel 的 doesntContain 方法提供了一種更直觀的方式來檢查字符串是否缺少特定內容。此方法是對現有 contains 方法的補充,為否定檢查提供了更簡潔的語法。

use Illuminate\Support\Str;

// 基本用法
$text = "Welcome to Laravel";
$result = Str::doesntContain($text, 'PHP'); // true
// 多重检查
$result = Str::doesntContain($text, ['PHP', 'Laravel']); // false
登入後複製

以下是一個實現消息過濾服務的實際示例:

<?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'];
    }
}
登入後複製

doesntContain 方法簡化了 Laravel 應用程序中的字符串驗證,為檢查特定內容的不存在提供了更直觀的語法。無論您是構建內容審核系統、輸入驗證還是數據過濾,此方法都能降低複雜性並提高代碼可讀性。結合 Laravel 的其他字符串輔助函數,它構成了一個用於高效字符串操作的綜合工具包。

以上是使用Laravel&#039; d dorntcontain檢查字符串缺失的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板