系统城装机大师 - 固镇县祥瑞电脑科技销售部宣传站!

当前位置:首页 > 网络编程 > PHP编程 > 详细页面

laravel框架实现敏感词汇过滤功能示例

时间:2020-02-15来源:系统城作者:电脑系统城

本文实例讲述了laravel框架实现敏感词汇过滤功能。分享给大家供大家参考,具体如下:

最近项目有需求,要对用户的签名,回复进行敏感词检测,然后搜到了一个好用的扩展,分享给大家。

https://github.com/FireLustre/php-dfa-sensitive

通过 composer 进行安装:


 
  1. composer require lustre/php-dfa-sensitive
  2.  

然后在 app 目录下创建 Services ,并添加 SensitiveWords.php


 
  1. <?php
  2. namespace App\Services;
  3. use DfaFilter\SensitiveHelper;
  4. class SensitiveWords
  5. {
  6. protected static $handle = null;
  7. private function __construct()
  8. {
  9. }
  10. private function __clone()
  11. {
  12. }
  13. /**
  14. * 获取实例
  15. */
  16. public static function getInstance($word_path = [])
  17. {
  18. if (!self::$handle) {
  19. //默认的一些敏感词库
  20. $default_path = [
  21. storage_path('dict/bk.txt'),
  22. storage_path('dict/fd.txt'),
  23. storage_path('dict/ms.txt'),
  24. storage_path('dict/qt.txt'),
  25. storage_path('dict/sq.txt'),
  26. storage_path('dict/tf.txt'),
  27. ];
  28. $paths = array_merge($default_path, $word_path);
  29. self::$handle = SensitiveHelper::init();
  30. if (!empty($paths)) {
  31. foreach ($paths as $path) {
  32. self::$handle->setTreeByFile($path);
  33. }
  34. }
  35. }
  36. return self::$handle;
  37. }
  38. /**
  39. * 检测是否含有敏感词
  40. */
  41. public static function isLegal($content)
  42. {
  43. return self::getInstance()->islegal($content);
  44. }
  45. /**
  46. * 敏感词过滤
  47. */
  48. public static function replace($content, $replace_char = '', $repeat = false, $match_type = 1)
  49. {
  50. return self::getInstance()->replace($content, $replace_char, $repeat, $match_type);
  51. }
  52. /**
  53. * 标记敏感词
  54. */
  55. public static function mark($content, $start_tag, $end_tag, $match_type = 1)
  56. {
  57. return self::getInstance()->mark($content, $start_tag, $end_tag, $match_type);
  58. }
  59. /**
  60. * 获取文本中的敏感词
  61. */
  62. public static function getBadWord($content, $match_type = 1, $word_num = 0)
  63. {
  64. return self::getInstance()->getBadWord($content, $match_type, $word_num);
  65. }
  66. }
  67.  

然后我们就可以在项目中,使用 SensitiveWords::getBadWord() 来获取文本中是否有敏感词。


 
  1. $bad_word = SensitiveWords::getBadWord($content);
  2. if (!empty($bad_word)) {
  3. throw new \Exception('包含敏感词:' . current($bad_word));
  4. }
  5.  

在 storage 目录下创建 dict 目录存放敏感词词库,bk.txt .....等等,这些词库都是我在网上下载的。

点击此处本站下载

更多关于Laravel相关内容感兴趣的读者可查看本站专题:《Laravel框架入门与进阶教程》、《php优秀开发框架总结》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家基于Laravel框架的PHP程序设计有所帮助。

分享到:

相关信息

系统教程栏目

栏目热门教程

人气教程排行

站长推荐

热门系统下载