当前位置:首页 > PHP教程 > php应用 > 列表

PHP屏蔽过滤指定关键字的方法

发布:smiling 来源: PHP粉丝网  添加日期:2021-04-21 11:05:17 浏览: 评论:0 

这篇文章主要介绍了PHP屏蔽过滤指定关键字的方法,包含了字符串的过滤处理与数组的遍历等技巧,非常具有实用价值,需要的朋友可以参考下

本文实例讲述了PHP屏蔽过滤指定关键字的方法。分享给大家供大家参考。具体分析如下:

实现思路:

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

二、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{ 
  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.  }//www.phpfensi.com 
  28. } 
  29. $content = '测试关键字'; 
  30. if ( banwordCheck($content, './banwords.txt') ){ 
  31.  echo "matched! "; 
  32. }else{ 
  33.  echo "no match! "; 
  34. } 

希望本文所述对大家的PHP程序设计有所帮助。

Tags: PHP屏蔽过滤关键字

分享到: