PHP-敏感詞彙過濾

方法一:

$sensitive = array(
    '小白', '小黑', 'me', 'you'
);
$badword = array_combine($sensitive,array_fill(0,count($sensitive),'*'));
$string = 'likeyou小白喜歡小黑愛着的大黃';
$str = strtr($string, $badword);
echo $str;

方法二:

function sensitive($list, $string){
    $count = 0; //違規詞的個數
    $sensitiveWord = '';  //違規詞
    $stringAfter = $string;  //替換後的內容
    $pattern = "/".implode("|",$list)."/i"; //定義正則表達式

    if(preg_match_all($pattern, $string, $matches)){ //匹配到了結果
        $patternList = $matches[0];  //匹配到的數組
        $count = count($patternList);
        $sensitiveWord = implode(',', $patternList); //敏感詞數組轉字符串
        $replaceArray = array_combine($patternList,array_fill(0,count($patternList),'*')); //把匹配到的數組進行合併,替換使用
        $stringAfter = strtr($string, $replaceArray); //結果替換
    }
    $log = "原句爲 [ {$string} ]<br/>";
    if($count==0){
        $log .= "暫未匹配到敏感詞!";
    }else{
        $log .= "匹配到 [ {$count} ]個敏感詞:[ {$sensitiveWord} ]<br/>".
            "替換後爲:[ {$stringAfter} ]";
    }
    return $log;
}

function testAction(){
    $string = 'likeyou小白喜歡小黑愛着的大黃'; //要過濾的內容
    $list = ['小明', '小紅', '大白', '小白', '小黑', 'me', 'you'];  //定義敏感詞數組
    $result = sensitive($list, $string);
    echo ($result);
    die;
}

方法三:

<?php
/**
 * 敏感詞過濾方法.
 */

namespace app\common\tool;


use app\common\model\Sensitive;

class SensitiveTool
{
    private static $arrHashMap = [];
    private static $file       = ROOT_PATH.'runtime'.DS.'sensitive.txt';

    /**
     * 把敏感詞保存爲文件
     * @return bool|int
     */
    public static function saveSensitiveWord(){
        $data = Sensitive::all();
        foreach( $data as $k => $v ){
            self::addKeyWord($v['name']);
        }
        return file_put_contents(self::$file,serialize(self::$arrHashMap));

    }

    /**
     * 過濾敏感詞
     * @param $strWord
     * @return mixed
     */
    public static function filterSensitiveWord( $strWord ){
        $file = unserialize(file_get_contents(self::$file));
        $resStr  = $strWord;
        if(!empty($file)){
            $len = mb_strlen($strWord, 'UTF-8');
            $arrHashMap = self::$arrHashMap = $file;
            $newWord = '';
            for ($i=0; $i < $len; $i++) {
                $word = mb_substr($strWord, $i, 1, 'UTF-8');
                if (!isset($arrHashMap[$word])) {
                    $arrHashMap = self::$arrHashMap;
                    $newWord = '';
                }
                $newWord .= $word;
                if ($arrHashMap[$word]['end']) {
                    $asterisk = self::getAsterisk(mb_strlen($newWord, 'UTF-8'));
                    $resStr = str_replace($newWord,$asterisk,$resStr);
                    $newWord = '';
                    $arrHashMap = self::$arrHashMap;
                } else{
                    $arrHashMap = $arrHashMap[$word];

                }
            }
        }

        return $resStr;
    }

    /**
     * 過濾郵箱和手機號(8位以上數字)
     * @param $msg
     * @return string
     */
    public static function filterTelMail( $msg ):string {
        if(is_string((string)$msg)){
            $msg = preg_replace('/\d{8,}/', '****', $msg);
            $msg = preg_replace('/[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})/i', '****', $msg);
        }else{
            $msg = '';
        }

        return $msg;
    }
    /**
     * 新增敏感詞的核心方法
     * @param $strWord
     */
    private static function addKeyWord( $strWord ) { //免定金峨眉牌汽槍
        $len = mb_strlen($strWord, 'UTF-8');

        $arrHashMap = &self::$arrHashMap;
        for ($i=0; $i < $len; $i++) {
            $word = mb_substr($strWord, $i, 1, 'UTF-8');
            // 已存在
            if (isset($arrHashMap[$word])) {
                if ($i == ($len - 1)) {
                    $arrHashMap[$word]['end'] = 1;
                }
            } else {
                // 不存在
                if ($i == ($len - 1)) {
                    $arrHashMap[$word] = [];
                    $arrHashMap[$word]['end'] = 1;
                } else {
                    $arrHashMap[$word] = [];
                    $arrHashMap[$word]['end'] = 0;
                }
            }
            // 傳址
            $arrHashMap = &$arrHashMap[$word];
        }
    }

    /**
     * 生成*號
     * @param int $num
     * @return string
     */
    private static function getAsterisk( int $num ) :string {
        $str = '';
        for($i=1;$i<=$num;$i++) {
            $str .= '*';
        }
        return $str;
    }

}

 

發佈了68 篇原創文章 · 獲贊 33 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章