PHP中如何筛选不包含任何禁用词的字符串?
检查PHP字符串是否不含禁用词的几种实现方法
方法1:循环遍历 + str_contains
这是最直观的实现,适合禁用词数量不多的场景。逐个遍历禁用词数组,用str_contains检查字符串是否包含当前词,一旦找到匹配就终止循环,避免多余计算。
$string = "a very long text ...."; $forbidden_words = array("word1", "word2", "word3"); $is_valid = true; foreach ($forbidden_words as $word) { if (str_contains($string, $word)) { $is_valid = false; break; } } if ($is_valid) { echo "字符串符合要求,不含禁用词"; } else { echo "字符串包含禁用词"; }
方法2:正则表达式批量检查
如果禁用词数量较多,用正则一次性匹配效率更高。需要先转义词中的正则特殊字符(比如.、*这类),避免正则解析出错,还可以添加i修饰符实现不区分大小写的匹配。
$string = "a very long text ...."; $forbidden_words = array("word1", "word2", "word3"); // 转义每个禁用词的正则特殊字符 $escaped_words = array_map('preg_quote', $forbidden_words); // 拼接成匹配任意禁用词的正则模式 $pattern = '/(' . implode('|', $escaped_words) . ')/i'; if (!preg_match($pattern, $string)) { echo "字符串符合要求,不含禁用词"; } else { echo "字符串包含禁用词"; }
方法3:array_filter 过滤匹配词
利用array_filter筛选出字符串中存在的禁用词,再判断结果数组是否为空,同时还能直接拿到具体的匹配词。
$string = "a very long text ...."; $forbidden_words = array("word1", "word2", "word3"); // 过滤出字符串中包含的禁用词 $matching_words = array_filter($forbidden_words, function($word) use ($string) { return str_contains($string, $word); }); if (empty($matching_words)) { echo "字符串符合要求,不含禁用词"; } else { echo "字符串包含禁用词:" . implode(', ', $matching_words); }
内容的提问来源于stack exchange,提问作者Mr.Verde
相关产品推荐
相关产品推荐

