laravel怎样对敏感词汇过滤?
Admin 2021-05-11 群英技术资讯 1582 次浏览
laravel框架怎样实现对敏感词汇过滤?在做开发的时候,有些需求需要对敏感词汇进行过滤,很多新手可能对此对如何实现这个功能不是很清楚,下面给大家分享一个对用户的签名,回复进行敏感词检测的实例,供大家参考学习。
通过 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实现敏感词汇过滤的代码,小编认为还是具有一定的参考价值的,有需要的朋友可以参考上文内容自己实现,希望本文对大家有帮助。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
php如何获取Http请求,php获取Http请求的方法及简单的示例如下,
安装swoole出现make报错的原因:找不到openssl/ssl.h,首先要确认电脑上有没有安装openssl。解决方法:使用命令“brew install openssl”安装openssl即可。
本篇文章整理分享六个能提高代码可读性的 Laravel Eloquent 小技巧,希望对大家有所帮助!
今天小编就为大家分享一篇关于PHP hex2bin()函数用法讲解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
php怎样现实上传和下载文件?很多网站都会提供文件的上传与下载功能,那么这一操作是如何实现的?下面是PHP实现对文件上传与下载操作的代码,有需要的朋友可做参考。
成为群英会员,开启智能安全云计算之旅
立即注册关注或联系群英网络
7x24小时售前:400-678-4567
7x24小时售后:0668-2555666
24小时QQ客服
群英微信公众号
CNNIC域名投诉举报处理平台
服务电话:010-58813000
服务邮箱:service@cnnic.cn
投诉与建议:0668-2555555
Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 ICP核准(ICP备案)粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008