首頁  >  文章  >  後端開發  >  php 屏蔽過濾指定關鍵字的方法

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

怪我咯
怪我咯原創
2017-07-12 14:51:163006瀏覽

這篇文章主要介紹了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]==&#39;&#39;){
continue; 
} 
// 如果检测到关键字,则返回匹配的关键字,并终止运行
if(@strpos($str,trim($arr[$i]))!==false){
//$i=$k; 
return $arr[$i];
} 
}
// 如果没有检测到关键字则返回false 
return false;
} 
$content = &#39;这里是要发布的文本内容。。。&#39;; 
// 过滤关键字
$keyWord = keyWordCheck($content);
// 判断是否存在关键字
if($keyWord){
echo &#39;你发布的内容存在关键字&#39;.$keyWord;
}else{
echo &#39;恭喜!通过关键字检测&#39;;
// 往下可以进行写库操作完成发布动作。
}

#範例2 (註:中文關鍵字過濾時使用的關鍵字檔案為utf-8編碼)

程式碼如下:

/**
 * 被禁止的关键字检测
 *
 * @param string $string  要检测的字符串
 * @param string $fileName 屏蔽关键字文件
 * @return bool
 */
function banwordCheck( $string, $fileName )
{
 if ( !($words = file_get_contents( $fileName )) ){
  die(&#39;file read error!&#39;);
 }
 $string = 
strtolower
($string);
 $matched = preg_match(&#39;/&#39;.$words.&#39;/i&#39;, $string, $result);
 if ( $matched && isset($result[0]) && strlen($result[0]) > 0 )
 {
  if ( strlen($result[0]) == 2 ){
   $matched = preg_match(&#39;/&#39;.$words.&#39;/iu&#39;, $string, $result);
  } 
  if ( $matched && isset($result[0]) && strlen($result[0]) > 0 ) {
   return true;
  }else{
   return false;
  }  
 }else{
  return false;
 }
}
$content = &#39;测试关键字&#39;;
if ( banwordCheck($content, &#39;./banwords.txt&#39;) ){
 echo "matched! ";
}else{
 echo "no match! ";
}

以上是php 屏蔽過濾指定關鍵字的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn