PHP屏蔽過濾指定關(guān)鍵字的方法
本文實例講述了PHP屏蔽過濾指定關(guān)鍵字的方法。分享給大家供大家參考。具體分析如下:
實現(xiàn)思路:
一、把關(guān)鍵字專門寫在一個文本文件里,每行一個,數(shù)量不限,有多少寫多少。
二、PHP讀取關(guān)鍵字文本,存入一個數(shù)組
三、遍歷關(guān)鍵字數(shù)組,挨個用strpos函數(shù)去看看內(nèi)容有沒有關(guān)鍵字,如果有,返回true,沒有則返回false
PHP代碼如下:
// 關(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)鍵字,并終止運行
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)鍵字檢測';
// 往下可以進行寫庫操作完成發(fā)布動作。
}
例子2 (注:中文關(guān)鍵字過濾時使用的關(guān)鍵字文件為utf-8編碼)
* 被禁止的關(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)文章
php ZipArchive實現(xiàn)多文件打包下載實例
在本篇文章里我們給各位整理了關(guān)于php ZipArchive實現(xiàn)多文件打包下載實例以及相關(guān)代碼,需要的朋友們可以學習下。2019-10-10
PHP Warning: Module ''modulename'' already loaded in問題解決辦法
這篇文章主要介紹了PHP Warning: Module 'modulename' already loaded in問題解決辦法,本文總結(jié)了兩種情況,需要的朋友可以參考下2015-03-03

