【问题标题】:Matching both preg_matches in an if statement在 if 语句中匹配两个 preg_matches
【发布时间】:2016-06-27 17:46:23
【问题描述】:

我在 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 )

【问题讨论】:

标签: php preg-match


【解决方案1】:

解释:-

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

如果您希望两者都作为输出,请使用 &amp;&amp; 而不是 ||,以便两者都会检查并打印

所以代码将是:-

<?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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-08
    • 1970-01-01
    • 2017-07-04
    • 2015-12-17
    • 1970-01-01
    • 2022-12-10
    相关资源
    最近更新 更多