在ThinkPHP框架中进行敏感词过滤可以使用ThinkPHP自带的validate类库或Thinkphp-extra的方法。具体步骤如下:
首先在应用目录下创建一个Common文件夹,并在该文件夹下创建一个function.php文件。
在function.php文件中定义一个方法,例如sensitiveWordFilter(),使用正则表达式或引入相关类库实现敏感词过滤。同时,可以使用相关函数对敏感词进行高亮显示。
在需要过滤敏感词的地方调用sensitiveWordFilter()方法即可。
以下是一个示例代码:
// Common/function.php
use Overtrue\Pinyin\Pinyin;
function sensitiveWordFilter($text, $highlight = true, $replaceChar = '*')
{
$pinyin = new Pinyin(); // 引入拼音依赖
// 敏感词数组(可以从数据库或缓存中获取)
$words = [
'政治', '法轮功',
];
$pattern = implode('|', array_map(function ($word) use ($pinyin) {
return sprintf('/%s|%s/', $word, $pinyin->abbr($word, ['only_chinese' => true])); // 加入拼音缩写匹配
}, $words));
if ($highlight) {
$text = preg_replace_callback($pattern, function ($match) use ($replaceChar) {
return '<span style="color: red">' . str_repeat($replaceChar, mb_strlen($match[0], 'UTF-8')) . '</span>';
}, $text);
} else {
$text = preg_replace($pattern, $replaceChar, $text);
}
return $text;
}
然后在控制器中调用该方法:
public function comment()
{
$comment = $_POST['comment'];
$filteredComment = sensitiveWordFilter($comment); // 进行敏感词过滤
echo $filteredComment;
}
在上面的代码中,使用了拼音缩写来匹配中文敏感词。同时,通过$highlight参数和$replaceChar参数,可以自定义是否对敏感词进行高亮显示以及高亮替换的字符。
值得注意的是,如果你的应用需要处理大量评论信息,在敏感词过滤时还应考虑性能优化,比如缓存常用敏感词等。