欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

laravel框架實現(xiàn)敏感詞匯過濾功能示例

 更新時間:2020年02月15日 09:01:55   作者:懷素真  
這篇文章主要介紹了laravel框架實現(xiàn)敏感詞匯過濾功能,結(jié)合實例形式分析了laravel框架通過擴展php-dfa-sensitive實現(xiàn)敏感詞過濾的相關(guān)操作技巧,需要的朋友可以參考下

本文實例講述了laravel框架實現(xiàn)敏感詞匯過濾功能。分享給大家供大家參考,具體如下:

最近項目有需求,要對用戶的簽名,回復(fù)進行敏感詞檢測,然后搜到了一個好用的擴展,分享給大家。

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

通過 composer 進行安裝:

composer require lustre/php-dfa-sensitive

然后在 app 目錄下創(chuàng)建 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 目錄下創(chuàng)建 dict 目錄存放敏感詞詞庫,bk.txt .....等等,這些詞庫都是我在網(wǎng)上下載的。

點擊此處本站下載

更多關(guān)于Laravel相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Laravel框架入門與進階教程》、《php優(yōu)秀開發(fā)框架總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總

希望本文所述對大家基于Laravel框架的PHP程序設(shè)計有所幫助。

相關(guān)文章

最新評論