PHP屏蔽关键字实现方法
方法一:
思路
用正则去匹配关键字,把关键字用别的字符替换:
$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 }