欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PHP屏蔽過濾指定關(guān)鍵字的方法

 更新時間:2014年11月03日 09:53:52   投稿:shichen2014  
這篇文章主要介紹了PHP屏蔽過濾指定關(guān)鍵字的方法,包含了字符串的過濾處理與數(shù)組的遍歷等技巧,非常具有實(shí)用價值,需要的朋友可以參考下

本文實(shí)例講述了PHP屏蔽過濾指定關(guān)鍵字的方法。分享給大家供大家參考。具體分析如下:

實(shí)現(xiàn)思路:

一、把關(guān)鍵字專門寫在一個文本文件里,每行一個,數(shù)量不限,有多少寫多少。
二、PHP讀取關(guān)鍵字文本,存入一個數(shù)組
三、遍歷關(guān)鍵字?jǐn)?shù)組,挨個用strpos函數(shù)去看看內(nèi)容有沒有關(guān)鍵字,如果有,返回true,沒有則返回false

PHP代碼如下:

復(fù)制代碼 代碼如下:
/* PHP中用strpos函數(shù)過濾關(guān)鍵字 */
// 關(guān)鍵字過濾函數(shù)
function keyWordCheck($content){
// 去除空白
$content = trim($content);
// 讀取關(guān)鍵字文本
$content = @file_get_contents('keyWords.txt');
// 轉(zhuǎn)換成數(shù)組
$arr = explode("n", $content);
// 遍歷檢測
for($i=0,$k=count($arr);$i<$k;$i++){
// 如果此數(shù)組元素為空則跳過此次循環(huán)
if($arr[$i]==''){
continue;
}
// 如果檢測到關(guān)鍵字,則返回匹配的關(guān)鍵字,并終止運(yùn)行
if(@strpos($str,trim($arr[$i]))!==false){
//$i=$k;
return $arr[$i];
}
}
// 如果沒有檢測到關(guān)鍵字則返回false
return false;
}
$content = '這里是要發(fā)布的文本內(nèi)容。。。';
// 過濾關(guān)鍵字
$keyWord = keyWordCheck($content);
// 判斷是否存在關(guān)鍵字
if($keyWord){
echo '你發(fā)布的內(nèi)容存在關(guān)鍵字'.$keyWord;
}else{
echo '恭喜!通過關(guān)鍵字檢測';
// 往下可以進(jìn)行寫庫操作完成發(fā)布動作。
}

例子2 (注:中文關(guān)鍵字過濾時使用的關(guān)鍵字文件為utf-8編碼)

復(fù)制代碼 代碼如下:
/**
 * 被禁止的關(guān)鍵字檢測
 *
 * @param string $string  要檢測的字符串
 * @param string $fileName 屏蔽關(guān)鍵字文件
 * @return bool
 */
function banwordCheck( $string, $fileName )
{
 if ( !($words = file_get_contents( $fileName )) ){
  die('file read error!');
 }
 $string = strtolower($string);
 $matched = preg_match('/'.$words.'/i', $string, $result);
 if ( $matched && isset($result[0]) && strlen($result[0]) > 0 )
 {
  if ( strlen($result[0]) == 2 ){
   $matched = preg_match('/'.$words.'/iu', $string, $result);
  }
  if ( $matched && isset($result[0]) && strlen($result[0]) > 0 ) {
   return true;
  }else{
   return false;
  } 
 }else{
  return false;
 }
}
$content = '測試關(guān)鍵字';
if ( banwordCheck($content, './banwords.txt') ){
 echo "matched! ";
}else{
 echo "no match! ";
}

希望本文所述對大家的PHP程序設(shè)計有所幫助。

相關(guān)文章

最新評論