將違禁詞彙存於陣列或文字檔,用戶提交內容時,以正則或字串搜尋進行攔截或替換。
function check_content($data) {
$keywords = '你是大神嗎|你好|去死'; // 以 | 分隔
if (preg_match("/$keywords/i", $data)) {
return false; // 含敏感詞,拒絕
}
return $data; // 通過
}
words.txt 格式:
|賭博機|賣血|出售腎|出售器官|眼角膜
過濾類別:
class WordFilter {
private $wordFile;
private $pattern;
public function __construct($file) {
$this->wordFile = $file;
$this->buildPattern();
}
private function buildPattern() {
$content = file_get_contents($this->wordFile);
if ($content === false) {
throw new Exception('敏感詞檔案讀取失敗');
}
// 清理格式:移除數字編號、多餘分隔符
$content = preg_replace("/[\d,\s\|]+/", '|', trim($content, '|'));
$this->pattern = '/(' . $content . ')/i';
}
public function filter($str, $replacement = '***') {
return preg_replace($this->pattern, $replacement, $str);
}
}
// 使用範例
$filter = new WordFilter('./words.txt');
$content = "<a href='#'>我要賭博機買血</a>";
echo $filter->filter($content); // 輸出:我要***買***
| 方案 | 適用規模 | 優點 | 缺點 |
|---|---|---|---|
| preg_match 陣列 | < 100 詞 | 簡單直觀 | 詞多時極慢 |
| preg_replace 詞庫 | < 5,000 詞 | 支援替換、檔案管理 | 正則回溯風險 |
| DFA/Trie 樹 | > 10,000 詞 | O(n) 掃描、記憶體友善 | 實作複雜 |