dscw1223 2016-06-17 17:05 采纳率: 50%
浏览 64
已采纳

带有if / else条件的php preg_match_all

I'm using the following 'badword filter' and it works -

    $question = Trim(stripslashes($_POST['Message']));     
    $badwords = array("caca","poopoo","pipi");
    $matches = array();
    $matchFound = preg_match_all("/\b(" . implode($badwords,"|") . ")\b/i", $question, $matches);
    if ($matchFound){
        $words = array_unique($matches[0]);
        foreach($words as $word){
            echo '<span class="word">'.$word.'</span>'; //outputs <span class="word">caca</span> <span class="word">poopoo</span> <span class="word">pipi</span>
        }
    }

My question is, I would like to add an if/else condition where if 3+ badwords are found, do this, and if not, do that. Pseudocode:

    if ($severalMatchesFound > 2){
        echo '3 or more badwords found';
    } else {
        echo 'less than 3 badwords found';
    }
  • 写回答

1条回答 默认 最新

  • dsf11t5u1651 2016-06-17 17:10
    关注
    $question = Trim(stripslashes($_POST['Message']));     
    $badwords = array("caca","poopoo","pipi");
    preg_match_all("/\b(" . implode($badwords,"|") . ")\b/i", $question, $matches);
    if (count($matches[1]) >= 3){
        // three words or more than three words
    
        $words = array_unique($matches[1]);
        foreach($words as $word){
            echo '<span class="word">'.$word.'</span>'; //outputs <span class="word">caca</span> <span class="word">poopoo</span> <span class="word">pipi</span>
        }
    }elseif(count($matches[1])>=1){
      //more than one but less than three
    }else{
      // no words found
    }
    

    Sorry forgot [1] on count. I think the elseif would have worked as I wrote it but isset is probably better

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100