首页 > 开发 > PHP > 正文

PHP中屏蔽过滤指定关键字实现方法总结

2024-05-04 21:58:47
字体:大 中 小
来源:转载
供稿:网友

我们经常会发现我们有提交留方的地方就会有很多的来发广告,后来想做一个屏蔽过滤指定关键字的功能,我搜索了几种方法介绍给大家有需要了解的朋友可参考.

思路:

一、把关键字专门写在一个文本文件里,每行一个,数量不限,有多少写多少.

二、PHP读取关键字文本,存入一个数组.

三、遍历关键字数组,挨个用strpos函数去看看内容有没有关键字,如果有,返回true,没有则返回false.

PHP代码如下:

  1. /* PHP中用strpos函数过滤关键字 */ 
  2. // 关键字过滤函数 
  3. function keyWordCheck($content){ 
  4. // 去除空白 
  5. $content = trim($content); 
  6. // 读取关键字文本 
  7. $content = @file_get_contents('keyWords.txt'); 
  8. // 转换成数组 
  9. $arr = explode("n", $content); 
  10. // 遍历检测 
  11. for($i=0,$k=count($arr);$i<$k;$i++){ 
  12. // 如果此数组元素为空则跳过此次循环 
  13. if($arr[$i]==''){ 
  14. continue;  
  15. }  
  16. // 如果检测到关键字,则返回匹配的关键字,并终止运行 
  17. if(@strpos($str,trim($arr[$i]))!==false){ 
  18. //$i=$k;  
  19. return $arr[$i]; 
  20. }  
  21. } 
  22. // 如果没有检测到关键字则返回false  
  23. return false; 
  24. }  
  25. $content = '这里是要发布的文本内容。。。';  
  26. // 过滤关键字 
  27. $keyWord = keyWordCheck($content); 
  28. // 判断是否存在关键字 
  29. if($keyWord){ 
  30. echo '你发布的内容存在关键字'.$keyWord; 
  31. }else{//开源代码Vevb.com 
  32. echo '恭喜!通过关键字检测'; 
  33. // 往下可以进行写库操作完成发布动作。 
  34. } 

例子2 ,注,中文关键字过滤时使用的关键字文件为utf-8编码,代码如下:

  1. /** 
  2.  * 被禁止的关键字检测 
  3.  * 
  4.  * @param string $string  要检测的字符串 
  5.  * @param string $fileName 屏蔽关键字文件 
  6.  * @return bool 
  7.  */ 
  8. function banwordCheck( $string, $fileName ) 
  9. { 
  10.  if ( !($words = file_get_contents( $fileName )) ){ 
  11.   die('file read error!'); 
  12.  } 
  13.  $string = strtolower($string); 
  14.  $matched = preg_match('/'.$words.'/i', $string, $result); 
  15.  if ( $matched && isset($result[0]) && strlen($result[0]) > 0 ) 
  16.  { 
  17.   if ( strlen($result[0]) == 2 ){ 
  18.    $matched = preg_match('/'.$words.'/iu', $string, $result); 
  19.   }  
  20.   if ( $matched && isset($result[0]) && strlen($result[0]) > 0 ) { 
  21.    return true; 
  22.   }else{ 
  23.    return false; 
  24.   }   
  25.  }else{ 
  26.   return false; 
  27.  } 
  28. } 
  29.  
  30. $content = '测试关键字'; 
  31. if ( banwordCheck($content, './banwords.txt') ){ 
  32.  echo "matched! "; 
  33. }else{ 
  34.  echo "no match! "; 
  35. } 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表