dscw1223
2016-06-17 17:05
浏览 55
已采纳

带有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

    点赞 评论

相关推荐 更多相似问题