带有if / else条件的php preg_match_all

时间:2016-06-17 17:05:18

标签: php preg-match-all

我正在使用以下“badword过滤器”并且它有效 -

    $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>
        }
    }

我的问题是,我想添加一个if / else条件,如果找到3个以上的坏词,请执行此操作,如果没有,请执行此操作。伪代码:

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

1 个答案:

答案 0 :(得分:0)

$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
}

抱歉忘了[1]。我认为elseif会像我写的那样工作但是isset可能更好