網站內容多為用戶生成(UGC),為符合法規需預先過濾敏感關鍵字。本文示範使用 strpos() 實現關鍵字檢測,並詳述從檔案讀取關鍵字時遇到的「隱形空白字元」陷阱及解決方案。
strpos() 檢測內容是否包含關鍵字<?php
function keyWordCheck($content) {
$content = trim($content);
// 讀取關鍵字檔案
$kw_content = @file_get_contents('keyWords.txt');
$arr = explode("\n", $kw_content);
for ($i = 0, $k = count($arr); $i < $k; $i++) {
if ($arr[$i] === '') continue; // 跳過空行
// 直接檢測,未處理換行符/空白
if (strpos($content, $arr[$i]) !== false) {
return $arr[$i]; // 回傳命中的關鍵字
}
}
return false;
}
?>
print_r() 顯示陣列正常 → 非讀取問題從文字檔 explode("\n") 產生的陣列元素,往往殘留 \r(Windows 換行符)或前後空白。導致 strpos($content, "關鍵字\r") 永遠不匹配。
<?php
function keyWordCheck($content) {
$content = trim($content);
$kw_content = @file_get_contents('keyWords.txt');
$arr = explode("\n", $kw_content);
for ($i = 0, $k = count($arr); $i < $k; $i++) {
if ($arr[$i] === '') continue;
// 關鍵修正:trim() 移除首尾空白與換行符
$keyword = trim($arr[$i]);
if (strpos($content, $keyword) !== false) {
return $keyword;
}
}
return false;
}
// 使用範例
$content = '這裡是要發布的內容,含有關鍵字2';
$kw = keyWordCheck($content);
if ($kw) {
echo '偵測到敏感詞:【' . $kw . '】';
} else {
echo '恭喜!通過關鍵字檢測';
}
?>