php過濾敏感詞庫演算法

2022-09-06 04:03:08 字數 1942 閱讀 3957

<?php

/** * created by phpstorm.

* user: administrator

* date: 2021/11/11

* time: 10:39

*/class filterwords

/*** 從檔案中載入敏感詞字典

*/protected function loaddataformfile($arr)

}/**

* 分割文字

* @param $str

* @return array|false|string

*/protected function splitstr($str)

/*** 新增敏感字至節點

* @param $words

*/protected function addwords($words)

$curnode = &$curnode[$char];

}//標記到達當前節點完整路徑為"敏感詞"

$curnode['end']++;

}/**

* 敏感詞校驗

* @param $str ;需要校驗的字串

* @param int $level ;遮蔽詞校驗等級 1-只要順序包含都遮蔽;2-中間間隔skipdistance個字元就遮蔽;3-全詞匹配即遮蔽

* @param int $skipdistance ;允許敏感詞跳過的最大距離,如笨aa蛋a傻瓜等等

* @param bool $isreplace ;是否需要替換,不需要的話,返回是否有敏感詞,否則返回被替換的字串

* @param string $replace ;替換字元

* @return bool|string

*/public function filter($str, $level = 1, $skipdistance = 2, $isreplace = true, $replace = '*')

elseif ($level == 2) else

$strarr = $this->splitstr($str);

$strlength = count($strarr);

$issensitive = false;

for ($i = 0; $i < $strlength; $i++)

$issensitive = true; //引用匹配到的敏感詞節點

$curnode = &$this->dict[$curchar];

$dist = 0;

$matchindex = [$i]; //匹配後續字串是否match剩餘敏感詞

for ($j = $i + 1; $j < $strlength && $dist < $maxdistance; $j++)

//如果匹配到的話,則把對應的字元所在位置儲存起來,便於後續敏感詞替換

$matchindex = $j;

//繼續引用

$curnode = &$curnode[$strarr[$j]];

}//判斷是否已經到敏感詞字典結尾,是的話,進行敏感詞替換

if (isset($curnode['end']) && $isreplace)

$i = max($matchindex);}}

if ($isreplace) else

}}

require_once "../../model/filterwords.php";

$data = json_decode(file_get_contents(spider_path."../sensitive"),true);

$filterwords = new filterwords($data);

$str = $filterwords->filter($str,1);

print_r($str);

PHP 實現敏感詞過濾(附敏感詞庫)

敏感詞 文字過濾是乙個 必不可少的功能,如何設計乙個好的 高效的過濾演算法是非常有必要的。在實現敏感詞過濾的演算法中,我們必須要減少運算,而dfa在dfa演算法中幾乎沒有什麼計算,有的只是狀態的轉換。所以想更高效的進行敏感詞的過濾,需要使用dfa演算法。但這裡展示的是使用php實現簡單的敏感詞過濾,...

php敏感詞過濾

1 簡單敏感詞過濾 badword array 張三 張三丰 張三丰田 badword1 array combine badword,array fill 0,count badword bb 我今天開著張三丰田上班 str strtr bb,badword1 echo str 2 使用php元件 ...

PHP 過濾敏感詞彙

方法一 sensitive array 小白 小黑 me you badword array combine sensitive,array fill 0,count sensitive string likeyou小白喜歡小黑愛著的大黃 str strtr string,badword echo ...