首页 > 后端开发 > php教程 > 使用Laravel' d dorntcontain检查字符串缺失

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

Karen Carpenter
发布: 2025-03-10 11:12:09
原创
746 人浏览过

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
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板