php處理敏感詞時遇到的相關編碼問題

2021-07-26 12:41:20 字數 1648 閱讀 3696

在過濾敏感詞這一塊,由於敏感詞數量較多,這時候就需要先構建乙個字典樹(trie),單純的字典樹占用空間較大,使用 double-array trie 或者 ternary search tree 可以在保證效能的同時節省一部分空間,但是敏感詞基本不會很多,幾千甚至上萬個詞基本沒壓力,所以就實現就選擇先構建乙個字典樹,然後逐字做匹配。

<?php

class sensitivewordfilter

private function initdict()

while (!feof($handle))

$uword = $this->unicodesplit($word);

$pdict = &$this->dict;

$count = count($uword);

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

$pdict = &$pdict[$uword[$i]];

}$pdict['end'] = true;

}fclose($handle);

}public function filter($str, $maxdistance = 5)

$ustr = $this->unicodesplit($str);

$count = count($ustr);

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

}if (isset($pdict['end']))

$ustr[$k] = '*';}}

}}return implode($ustr);

}public function unicodesplit($str)

} else if (($c & 0xf0) == 0xe0 && $len - $i >= 3)

} else if (($c & 0xe0) == 0xc0 && $len - $i >= 2)

}} else

}return $ret;}}

使用方法

<?php

require 'sensitivewordfilter.php';

$filter = new sensitivewordfilter(__dir__ . '/sensitive_words.txt');

$filter->filter('這是乙個敏感詞', 10);

其中,unicodesplit函式實現將從檔案中獲取的漢字,乙個乙個分離出來,那麼,判斷每個漢字占用幾個位元組,是該函式的關鍵所在,該演算法針對utf-8編碼。

utf-8格式位元組

4中情況分別是:

1、乙個位元組: 0******x,低7位為有效資料,內碼是0x0~0x7f

2、兩個位元組: 110***xx 10yyyyyy,低5位+低6位為有效資料,內碼是0x80~0x7ff

3、三個位元組:1110***x 10yyyyyy 10zzzzzz,低4位+低6位+低6位 為有效資料,內碼是0x800~0xffff,除掉幾個保留的特殊內碼

4、四個位元組: 11110aaa 10****** 10****** 10******,低3位 +低6位 +低6位 +低6位為有效資料,內碼是0x10000~0x10ffff

按前面1的個數就能區分每個字佔了多少個位元組。

這就是為什麼unicodesplit會出現0x80,0xf0,0xe0,0xc0,

mysql 敏感詞 PHP實現的敏感詞過濾方法示例

1 敏感詞過濾方法 todo 敏感詞過濾,返回結果 param array list 定義敏感詞一維陣列 param string string 要過濾的內容 return string log 處理結果 function sensitive list,string if count 0 else ...

檢測敏感詞的 PHP 擴充套件

敏感詞過濾是我朝程式設計師必須具備的一種特殊技能,隨著敏感詞越來越多,是時候寫個擴充套件來快速的進行敏感詞檢測了 使用說明 1.安裝 libdatrie tar zxf libdatrie 0.2.4.tar.gz cd libdatrie 0.2.4 configure prefix usr lo...

php敏感字串過濾 PHP實現的敏感詞過濾方法

php實現的敏感詞過濾方法,以下是乙份過濾敏感詞的編碼。有需要可以參考參考。todo 敏感詞過濾,返回結果 param array list 定義敏感詞一維陣列 param string string 要過濾的內容 return string log 處理結果 function sensitive ...