2019-08-28 11:53:54
围观(8076)
博客或者论坛及各种 APP 都会用到评论/发布功能。为避免被恶意用于发布不友好内容,所以就需要检测敏感词或者过滤敏感词。
检测过滤敏感词,需要先有一个敏感词库,当然你也可以使用阿里云或其他 IDC 提供的敏感词接口(就不用自己写接口,没下面这些事了)
敏感词库因为太敏感了,所以就不提供了。如果真的需要可以在本文下方评论联系方式。 Tips:词库在 Github 上也有很多。
当然也可以自己创造词库,先创建一个文档 后缀名为.txt 的。然后将敏感词写入,一行一个敏感词。
比如这样
1 2 3 | 我日 暴力 卧槽 |
保存好之后就可以使用下面这段代码引入该文件,一个检测过滤敏感词的接口就好了。
比如创建个 api.php 写入代码并配好环境:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | <?php header( 'Content-type: text/json' ); $content = isset( $_POST [ 'content' ]) ? $_POST [ 'content' ] : null; if (! $content ){ return_json(301, '请提交需要检测的内容' ); } if ( $res = check_content( $content )){ if (isset( $_POST [ 'method' ]) && $_POST [ 'method' ] == 1){ //过滤敏感词 $content = str_replace ( $res , '*' , $content ); return_json(201, '检测到敏感词:' . $res , $content ); } return_json(201, '检测到敏感词:' . $res ); } return_json(200, '没有检测到敏感词' ); function check_content( $content ) { $file = 'words.txt' ; //上面这个就是词库文件路径 $sensitive_array = array_map ( 'rtrim' , file( $file )); foreach ( $sensitive_array as $key => $value ) { if ( $value == '' ){ continue ; } if (mb_strpos( $content , $value ) != false){ return $value ; //return true; } } return false; } function return_json( $code , $msg , $data = '' ){ exit (json_encode([ 'code' => $code , 'msg' => $msg , 'data' => $data , ])); } ?> |
接口提交方式: POST
所需参数: content(必须), method(可选)(值为1)
返回参数: code => 数据正常无敏感词返回 200, 数据存在敏感词返回 201, 没有提交需要检测的内容返回 301
msg => 返回提示 + 敏感词, 无敏感词则返回提示
data => 当接口请求时携带 method 参数且值为 1 时,返回过滤好的内容。(无敏感内容或不携带 method 参数时,该参数返回的结果均为空)
以下是使用 Postman 测试的结果
检测内容存在敏感词,但不携带 method 参数:
检测内容存在敏感词,携带 method 且值为 1:
检测无敏感内容:
本文地址 : bubaijun.com/page.php?id=133
版权声明 : 未经允许禁止转载!
上一篇文章: 开源PHP轮询即时聊天—群聊
下一篇文章: PHP爬取某招聘网站职业分类及公众号内容
不败君
板凳
@linlinzzo https://gitee.com/ailir/tools/tree/master/ https://gitee.com/fastjee/sensitive-words 敏感词内容真的很敏感,不敢放博客上😂 这里有两个地址你进去就有词库了。
评论时间:2021-02-05 11:30:53
@不败君 500星,腾讯离线库:/cjh0613/tencent-sensitive-words 900星,16年老库:/fwwdn/sensitive-stop-words 1.9k星,21年1w词库:/observerss/textfilter 免责声明:资源来自网络,仅用于学习交流,请勿用于非法用途!
评论时间:2023-05-28 10:01:17