laravel框架實現敏感詞彙過濾功能示例
阿新 • • 發佈:2020-02-17
本文例項講述了laravel框架實現敏感詞彙過濾功能。分享給大家供大家參考,具體如下:
最近專案有需求,要對使用者的簽名,回覆進行敏感詞檢測,然後搜到了一個好用的擴充套件,分享給大家。
https://github.com/FireLustre/php-dfa-sensitive
通過 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,$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相關內容感興趣的讀者可檢視本站專題:《Laravel框架入門與進階教程》、《php優秀開發框架總結》、《php面向物件程式設計入門教程》、《php+mysql資料庫操作入門教程》及《php常見資料庫操作技巧彙總》
希望本文所述對大家基於Laravel框架的PHP程式設計有所幫助。