1、扩展安装
composer require lustre/php-dfa-sensitive
2、推荐的敏感词库
https://codeload.github.com/jkiss/sensitive-words/zip/refs/heads/master
3、使用:
把下载好的词库放到项目本地
直接上代码:
use DfaFilterSensitiveHelper;
public static function checkSensitiveWords($words) { $route = __DIR__. '/../extends/Sensitive_words.txt'; $word = file_get_contents($route); $sensitiveWords = explode(",",$word); $handle = SensitiveHelper::init()->setTree($sensitiveWords);//构建敏感词库树 $isLegal = $handle->islegal($words);//是否有敏感词 if($isLegal) { $words = $handle->replace($words, '***');//敏感词替换成*** } return $words; }
参考地址:https://packagist.org/packages/lustre/php-dfa-sensitive