Laravel敏感词过滤实现方案
本例详细解析如何在Laravel框架中构建敏感词汇过滤机制,供开发者参考实践。
近期项目需对用户签名及评论实施敏感词筛查,经调研发现一款实用的扩展包,现分享使用心得。
相关开源项目地址:https://github.com/FireLustre/php-dfa-sensitive
首先通过 Composer 工具完成依赖安装:
composer require lustre/php-dfa-sensitive
随后在 app 目录下新建 Services 文件夹,并创建 SensitiveWords.php 服务类。
<?php
namespace App\Services;
use DfaFilter\SensitiveHelper;
class SensitiveWords
{
protected static $handle = null;
private function __construct()
{
}
private function __clone()
{
}
/**
* 获取实例
*/
public static function getInstance($word_path = [])
{
if (!self::$handle) {
//默认的一些敏感词库
$default_path = [
storage_path('dict/bk.txt'),
storage_path('dict/fd.txt'),
storage_path('dict/ms.txt'),
storage_path('dict/qt.txt'),
storage_path('dict/sq.txt'),
storage_path('dict/tf.txt'),
];
$paths = array_merge($default_path, $word_path);
self::$handle = SensitiveHelper::init();
if (!empty($paths)) {
foreach ($paths as $path) {
self::$handle->setTreeByFile($path);
}
}
}
return self::$handle;
}
/**
* 检测是否含有敏感词
*/
public static function isLegal($content)
{
return self::getInstance()->islegal($content);
}
/**
* 敏感词过滤
*/
public static function replace($content, $replace_char = '', $repeat = false, $match_type = 1)
{
return self::getInstance()->replace($content, $replace_char, $repeat, $match_type);
}
/**
* 标记敏感词
*/
public static function mark($content, $start_tag, $end_tag, $match_type = 1)
{
return self::getInstance()->mark($content, $start_tag, $end_tag, $match_type);
}
/**
* 获取文本中的敏感词
*/
public static function getBadWord($content, $match_type = 1, $word_num = 0)
{
return self::getInstance()->getBadWord($content, $match_type, $word_num);
}
}
配置完成后,即可在业务逻辑中调用 SensitiveWords::getBadWord() 来检测文本是否包含敏感词汇。
$bad_word = SensitiveWords::getBadWord($content);
if (!empty($bad_word)) {
throw new \Exception('包含敏感词:' . current($bad_word));
}
需在 storage 目录下建立 dict 子目录以存储词库文件(如 bk.txt 等),这些词库资源多来源于网络下载。
如需获取基础词库,可点击此处本站下载。
期望上述方案能为基于 Laravel 的 PHP 开发提供有益帮助。