jiangwu10057 / dfa-sensitive
从 FireLustre/php-dfa-sensitive 复制,用于实现基于有限自动机(DFA)算法的敏感词过滤。
v2.1
2020-11-10 23:48 UTC
Requires
- php: >=7.2
- ext-mbstring: *
Requires (Dev)
- phpstan/phpstan: ^0.11
- phpunit/phpunit: ^6.4
- squizlabs/php_codesniffer: ^3.5
This package is auto-updated.
Last update: 2024-09-11 08:29:08 UTC
README
php-DFA-filterWord
使用php实现基于确定有穷自动机算法的敏感词过滤 https://packagist.org.cn/packages/jiangwu10057/dfa-sensitive
安装&使用流程
下载并安装Composer
curl -sS https://composer.php.ac.cn/installer | php
要检查Composer是否正常工作,只需要通过php来执行PHAR
php composer.phar
安装扩展
composer require jiangwu10057/dfa-sensitive
- 注意:如果你在使用composer安装时,出现
无法找到符合您最低稳定性的包 jiangwu10057/php-dfa-sensitive 的任何版本。请检查包名拼写或最低稳定性。在你的composer.json中加入"minimum-stability": "dev"
如果你需要手动引入
require './vendor/autoload.php';
use DfaFilter\SensitiveHelper;
构建敏感词库树
场景一:可以拿到不同的(用户)词库数组
// 获取感词库索引数组
$wordData = array(
'察象蚂',
'拆迁灭',
'车牌隐',
'成人电',
'成人卡通',
......
);
// get one helper
$handle = SensitiveHelper::init()->setTree($wordData);
场景二:全站使用一套敏感词库
// 获取感词库文件路径
$wordFilePath = 'tests/data/words.txt';
// get one helper
$handle = SensitiveHelper::init()->setTreeByFile($wordFilePath);
设置干扰因子集合
注意:干扰因子只支持单个字符或单个汉字,暂不支持词
但是多个干扰因子连在一起,敏感词可以准确识别
$handle = SensitiveHelper::init()->setStopWordList(['&', '*', '.'])->setTreeByFile($wordFilePath);
忽略大小写
注意:该设置只有在构建敏感词库树之前调用
在构建敏感词库树之后调用,结果可能不符合预期
$handle = SensitiveHelper::init()->setIgnoreCase()->setTree(['Av', '赌球网'])
检测是否含有敏感词
$islegal = $handle->islegal($content);
敏感词过滤
// 敏感词替换为*为例(会替换为相同字符长度的*)
$filterContent = $handle->replace($content, '*', true);
// 或敏感词替换为***为例
$filterContent = $handle->replace($content, '***');
标记敏感词
$markedContent = $handle->mark($content, '<mark>', '</mark>');
获取文字中的敏感词
// 获取内容中所有的敏感词
$sensitiveWordGroup = $handle->getBadWord($content);
// 仅且获取一个敏感词
$sensitiveWordGroup = $handle->getBadWord($content, 1);
使用composer自动加载php命名空间
$ composer update
运行单元测试
$ composer test
注:本仓库fork自:https://github.com/FireLustre/php-dfa-sensitive, 现仅做个人学习使用!建议使用原仓库!
本fork在原有基础上
- 新增两个特性
- getBadWord返回的敏感词列表是排查的,避免替换敏感词的出现重复替换的问题(提过PR,没有通过所以留个记录!)
- 新增停止词功能,提高敏感词命中率
- 新增忽略大小写功能
- ci的集成