黑帽联盟

 找回密码
 会员注册
查看: 1483|回复: 0

[php] 屏蔽过滤指定关键字的方法

[复制链接]

852

主题

38

听众

3168

积分

白金VIP

Rank: 8Rank: 8

  • TA的每日心情
    开心
    2024-3-7 12:52
  • 签到天数: 1538 天

    [LV.Master]伴坛终老

    通过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. }
    28. }
    29. $content = '测试关键字';
    30. if ( banwordCheck($content, './banwords.txt') ){
    31. echo "matched! ";
    32. }else{
    33. echo "no match! ";
    34. }
    复制代码
    勿忘初心,方得始终!
    您需要登录后才可以回帖 登录 | 会员注册

    发布主题 !fastreply! 收藏帖子 返回列表 搜索
    回顶部