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

來源:互聯網
上載者:User
這篇文章主要介紹了PHP屏蔽過濾指定關鍵字的方法,包含了字串的過濾處理與數組的遍曆等技巧,非常具有實用價值,需要的朋友可以參考下

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

實現思路:

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

PHP代碼如下:

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

例子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! ";}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.