方法一:
思路
用正則去匹配關鍵字,把關鍵字用別的字符替換:
1
2
3
|
$str = "/你大爺|你麻痹|什么玩意|SB|你他媽/" ; // 關鍵字正則字符串
$string = "你他媽干什么玩意了 SB" ; // 文本字符串
echo preg_replace( $str , "*" , $string ); //preg_replace() 執行一個正則表達式的匹
|
方法二:
思路
1.把關鍵字放到一個txt文檔中 要用一定的符合分隔開 ,用file_get_contents() 函數將關鍵字文檔讀入
2.用函數explode() 把字符串分割成數組 循環數組 strpos() 查找匹配關鍵字
1 header('content-type:textml; charset=utf-8;'); 2 function strPosFuck($content){ 3 $fuck = file_get_contents('keyWords.txt'); // 讀取關鍵字文本信息
4 $content = trim($content); $fuckArr = explode("\n",$fuck); // 把關鍵字轉換為數組
5 for ($i=0; $i < count($fuckArr) ; $i++){ 6 // $fuckArr[$i] = trim($fuckArr[$i]);
7 if ($fuckArr[$i] == "") { 8 continue; //如果關鍵字為空就跳過本次循環
9 # code...
10 } 11 if (strpos($content,trim($fuckArr[$i])) != false){ 12 return $fuckArr[$i]; //如果匹配到關鍵字就返回關鍵字
13 # code...
14 } 15 } 16 return false; // 如果沒有匹配到關鍵字就返回 false
17 } 18 $content = "我今天你大爺碰到一個SB"; 19 $key = strPosFuck($content); 20 if ($key){ 21 echo "存在關鍵字".$key; 22 # code...
23 }else{ 24 echo "OK"; 25 }
注意點 一定要去空 一定要去空 ,
strops() 函數返回值 要么是false 要么就是關鍵字的位置 判斷的時候注意
方法三:
1 /** 2 * 被禁止的關鍵字檢測 3 * 4 * @param string $string 要檢測的字符串 5 * @param string $fileName 屏蔽關鍵字文件 6 * @return bool 7 */
8 function banwordCheck( $string, $fileName ){ 9 if ( !($words = file_get_contents( $fileName )) ){ 10 die('file read error!'); 11 } 12 $string = strtolower($string); 13 $matched = preg_match('/'.$words.'/i', $string, $result); 14 if ( $matched && isset($result[0]) && strlen($result[0]) > 0 ){ 15 if ( strlen($result[0]) == 2 ){ 16 $matched = preg_match('/'.$words.'/iu', $string, $result); 17 } 18 if ( $matched && isset($result[0]) && strlen($result[0]) > 0 ) { 19 return true; 20 }else{ 21 return false; 22 } 23 }else{ 24 return false; 25 } 26 } 27 $content = '測試關鍵字'; 28 if ( banwordCheck($content, './banwords.txt') ){ 29 echo "matched! "; 30 }else{ 31 echo "no match! "; 32 }