当前位置:首页 > CMS教程 > 其它CMS > 列表

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

发布:smiling 来源: PHP粉丝网  添加日期:2022-02-12 10:41:31 浏览: 评论:0 

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

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

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

通过 composer 进行安装:

composer require lustre/php-dfa-sensitive

然后在 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 (!emptyempty($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. } 

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

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

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

Tags: laravel敏感词汇过滤

分享到: