匹配if语句中的preg_matches

时间:2016-06-26 18:05:37

标签: php preg-match

我在if语句中有2个preg_match,if其中任何一个都是真的,我想打印它们两个。但由于某些原因,每次只匹配第一个preg_match,即使它们都具有相同的模式。为什么会这样?

<?php

$string = "how much is it?";
if (preg_match("~\b(how (much|many))\b~", $string, $match1) || preg_match("~\b(how (much|many))\b~", $string, $match2)) {
print_r($match1);
print_r($match2);   
}

?>

结果:

Array ( [0] => how much [1] => how much [2] => much )

预期结果:

Array ( [0] => how much [1] => how much [2] => much )
Array ( [0] => how much [1] => how much [2] => much )

1 个答案:

答案 0 :(得分:3)

说明: -

由于||条件,当第一个一次正确时,如果通过忽略第二个来执行。所以第一个输出数组,但第二个输出Notice: Undefined variable: match2 in D:\xampp\htdocs\abc.php on line 6。你没有得到那个错误是很奇怪的。

如果您希望两者都作为输出使用&&而不是||,那么两者都会检查并且两者都会打印

所以代码将是: -

<?php

$string = "how much is it?";
if (preg_match("~\b(how (much|many))\b~", $string, $match1) && preg_match("~\b(how (much|many))\b~", $string, $match2)) {
print_r($match1);
print_r($match2);   
}

?>

输出: - https://eval.in/595814

另一种解决方案: -

<?php
    $string = "how much is it?";
    preg_match("~\b(how (much|many))\b~", $string, $match1);
    preg_match("~\b(how (much|many))\b~", $string, $match2);
    print_r($match1);
    print_r($match2);   
?>

更多学习内容: - http://php.net/manual/en/language.operators.logical.php