php preg_match_all 条件为 if/else
php preg_match_all with if/else condition
我正在使用以下 'badword filter' 并且它有效 -
$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';
}
$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 可能更好
我正在使用以下 'badword filter' 并且它有效 -
$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';
}
$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 可能更好