php实现词语过滤
PHP实现词语过滤的方法
使用PHP实现词语过滤可以通过多种方式完成,以下是几种常见的方法:
使用str_replace函数进行简单替换
$text = "这是一段包含敏感词的文本";
$badWords = ["敏感词", "不良词"];
$replacement = "*";
$filteredText = str_replace($badWords, $replacement, $text);
使用正则表达式进行更复杂的匹配
$text = "包含SensitiveWord的文本";
$pattern = '/sensitiveword/i'; // i表示不区分大小写
$filteredText = preg_replace($pattern, '*', $text);
创建自定义过滤函数
function filterWords($text, $badWords, $replacement = '*') {
foreach($badWords as $word) {
$pattern = '/'.preg_quote($word, '/').'/i';
$text = preg_replace($pattern, $replacement, $text);
}
return $text;
}
$text = "测试敏感词过滤功能";
$badWords = ["敏感词", "测试"];
echo filterWords($text, $badWords);
使用数组和匿名函数进行高效过滤
$text = "这段文本需要过滤badword1和BADWORD2";
$badWords = ['badword1', 'badword2'];
$filteredText = array_reduce($badWords, function($carry, $word) {
return preg_replace("/$word/i", '*', $carry);
}, $text);
从文件或数据库加载敏感词列表
// 从文件加载
$badWords = file('badwords.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
// 从数据库加载
$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
$stmt = $pdo->query('SELECT word FROM bad_words');
$badWords = $stmt->fetchAll(PDO::FETCH_COLUMN);
使用mb_string函数处理多字节字符
$text = "包含日本語の不適切な言葉";
$badWords = ["不適切", "言葉"];
foreach($badWords as $word) {
if(mb_strpos($text, $word) !== false) {
$text = str_replace($word, '*', $text);
}
}
实现模糊匹配过滤
function fuzzyFilter($text, $badWords, $threshold = 70) {
foreach($badWords as $word) {
similar_text(strtolower($text), strtolower($word), $percent);
if($percent >= $threshold) {
$text = preg_replace('/'.$word.'/i', '*', $text);
}
}
return $text;
}
使用第三方库
可以考虑使用专门的过滤库如:
voku/stop-wordsjames-heinrich/php-stop-words
这些方法可以根据具体需求选择或组合使用,实现不同级别的词语过滤功能。







