PHP屏蔽過濾指定關(guān)鍵字的方法
本文實(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代碼如下:
// 關(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編碼)
* 被禁止的關(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+HTML+JavaScript+Css實(shí)現(xiàn)簡單爬蟲開發(fā)
這篇文章主要為大家詳細(xì)介紹了PHP+HTML+JavaScript+Css實(shí)現(xiàn)簡單爬蟲開發(fā),具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-03-03非集成環(huán)境的php運(yùn)行環(huán)境(Apache配置、Mysql)搭建安裝圖文教程
這篇文章主要介紹了非集成環(huán)境的php運(yùn)行環(huán)境(Apache配置、Mysql)搭建安裝圖文教程,感興趣的小伙伴們可以參考一下2016-04-04/etc/php-fpm.d/www.conf 配置注意事項
下面小編就為大家?guī)硪黄?etc/php-fpm.d/www.conf 配置注意事項。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02