You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中实现用户帖子指定词片段过滤的技术问题咨询

违规词过滤代码完善方案

嘿,我看你正在写用户帖子的违规词移除代码,已经搭好基础框架了,我来帮你补全并优化一下,让它更实用!

首先先把你现有的代码整理出来:

$badWords = array("damn", "hell", "fool"); //定义包含所有违规词的数组
$txtlower = strtolower($text); //将整个文本转为小写
foreach ($badWords as $word) { //遍历数组,$word依次代表每个违规词
    if (strpos($txtlower, $word) !== false) { //检查小写文本中是否存在该违规词
        // 这里需要补充替换逻辑
    }
}

你的思路是对的:统一转小写来做不区分大小写的匹配,接下来我们可以补充两种常见的过滤逻辑,按需选择。

方案1:整词匹配替换(推荐,避免误杀正常词汇)

这种方式会只匹配独立的违规词,不会替换掉包含违规词的正常词汇(比如不会把"foolish"里的"fool"替换掉),同时支持不区分大小写匹配:

$badWords = array("damn", "hell", "fool");
$text = "Oh Damn, that's a foolish Hell of a problem! Don't be a fool.";

// 构建正则匹配规则:匹配整词、转义特殊字符、不区分大小写
$patterns = array_map(function($word) {
    // \b 表示单词边界,preg_quote转义违规词中的特殊正则字符
    return '/\b' . preg_quote($word, '/') . '\b/i';
}, $badWords);

// 生成对应长度的星号替换符
$replacements = array_map(function($word) {
    return str_repeat('*', strlen($word));
}, $badWords);

// 执行替换
$filteredText = preg_replace($patterns, $replacements, $text);

echo $filteredText;
// 输出结果:Oh ****, that's a foolish **** of a problem! Don't be a ****.

方案2:全片段匹配替换(严格过滤所有包含违规词的内容)

如果你需要严格过滤所有出现违规词片段的内容(比如"foolish"里的"fool"也会被替换),可以用不区分大小写的字符串替换:

$badWords = array("damn", "hell", "fool");
$text = "Oh Damn, that's a foolish Hell of a problem!";

// 生成对应长度的星号替换符
$replacements = array_map(function($word) {
    return str_repeat('*', strlen($word));
}, $badWords);

// str_ireplace 支持不区分大小写的数组替换
$filteredText = str_ireplace($badWords, $replacements, $text);

echo $filteredText;
// 输出结果:Oh ****, that's a ****ish **** of a problem!

额外提示

  • 如果你的违规词里包含正则特殊字符(比如$、.、*),一定要用preg_quote转义,避免正则表达式出错;
  • 如果需要处理更复杂的场景(比如违规词的变形、同义词),可以考虑扩展违规词数组,或者使用专门的内容过滤库,但上面的代码足以应对大部分基础场景。

内容的提问来源于stack exchange,提问作者Vlad77

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:27:52