PHP如何实现消息字段包含指定词汇时拦截表单提交?
问题根因
stripos() 函数的第二个参数仅支持传入字符串类型,你直接传入数组会触发类型错误,无法得到预期的匹配结果,这是代码失效的核心原因。
解决方案
方案1:遍历数组逐个检测
这种方法逻辑直观,匹配到首个违禁词就可以提前终止遍历,性能开销低,适合违禁词数量较多的场景。
//Prevent the form from submission if it contains one, two, or three $needle = ['one', 'two', 'three']; $invalid = false; foreach ($needle as $word) { if (stripos($message, $word) !== false) { $invalid = true; // 匹配到后直接跳出循环,不需要继续检测剩余词汇 break; } } if ($invalid) { echo 'invalid message format'; // 此处添加阻止表单提交的后续逻辑 }
方案2:正则表达式批量检测
通过正则规则合并所有违禁词,代码更简洁,适合违禁词数量较少的场景。注意要对关键词做正则转义,避免关键词包含正则特殊字符时匹配出错。
//Prevent the form from submission if it contains one, two, or three $needle = ['one', 'two', 'three']; // 拼接正则规则,末尾i标识忽略大小写,对应stripos的不区分大小写特性 $pattern = '/' . implode('|', array_map('preg_quote', $needle)) . '/i'; if (preg_match($pattern, $message)) { echo 'invalid message format'; // 此处添加阻止表单提交的后续逻辑 }
内容的提问来源于stack exchange,提问作者Abe
相关产品推荐
相关产品推荐

