网问答>>PHP实现的敏感词过滤方法
问题
已解决

PHP实现的敏感词过滤方法

时间:2026-03-13 04:24:33
PHP实现的敏感词过滤方法
最佳回答
PHP实现的敏感词过滤方法通常涉及正则表达式匹配和字符串替换。以下是一个基于正则表达式的敏感词过滤实现方案,包含详细代码示例和说明:核心实现代码/ * 敏感词过滤函数 * @param array $sensitiveList 敏感词数组 * @param string $content 待检测文本 * @param string $replaceChar 替换字符(默认*) * @return array 包含处理结果和日志信息的数组 */function filterSensitiveWords($sensitiveList, $content, $replaceChar = *) { // 预处理敏感词数组(转义正则特殊字符) $escapedList = array_map(preg_quote, $sensitiveList); // 构建正则模式(不区分大小写) $pattern = /.implode(|, $escapedList)./iu; // 初始化结果 $result = [ original = $content, filtered = $content, count = 0, matched_words = [], log = ]; // 执行匹配 if (preg_match_all($pattern, $content, $matches)) { $result[matched_words] = array_unique($matches[0]); $result[count] = count($result[matched_words]); // 创建替换映射(保持原长度替换) $replaceMap = []; foreach ($result[matched_words] as $word) { $replaceMap[$word] = str_repeat($replaceChar, mb_strlen($word)); } $result[filtered] = strtr($content, $replaceMap); } // 生成日志 $result[log] = sprintf( "原始文本: %sn", $result[original] ); if ($result[count] 0) { $result[log] .= sprintf( "检测到 %d 个敏感词: %sn过滤后文本: %s", $result[count], implode(, , $result[matched_words]), $result[filtered] ); } else { $result[log] .= "未检测到敏感词"; } return $result;}使用示例// 测试数据$sensitiveWords = [暴力, 赌博, 毒品, 诈骗, 色情];$testContent = "这是一个包含赌博和色情内容的测试文本,需要过滤掉违禁词。";// 执行过滤$filterResult = filterSensitiveWords($sensitiveWords, $testContent);// 输出结果echo "pre".$filterResult[log]."/pre";/* 预期输出:原始文本: 这是一个包含赌博和色情内容的测试文本,需要过滤掉违禁词。检测到 2 个敏感词: 赌博, 色情过滤后文本: 这是一个包含和内容的测试文本,需要过滤掉违禁词。*/优化建议性能优化:对于大量敏感词(1000),建议使用Trie树算法替代正则表达式可缓存预处理后的正则模式功能增强:// 添加白名单支持function filterWithWhitelist($sensitiveList, $whitelist, $content) { $filtered = $content; foreach ($sensitiveList as $word) { if (!in_array($word, $whitelist)) {
时间:2026-03-13 04:24:40
本类最有帮助
Copyright © 2008-2013 www.wangwenda.com All rights reserved.冀ICP备12000710号-1
投诉邮箱: