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

PHP屏蔽過濾指定關鍵字的方法

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

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

實現(xiàn)思路:

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

PHP代碼如下:

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

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

復制代碼 代碼如下:
/**
 * 被禁止的關鍵字檢測
 *
 * @param string $string  要檢測的字符串
 * @param string $fileName 屏蔽關鍵字文件
 * @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 = '測試關鍵字';
if ( banwordCheck($content, './banwords.txt') ){
 echo "matched! ";
}else{
 echo "no match! ";
}

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

相關文章

最新評論