dongming6201 2016-06-26 18:05
浏览 13
已采纳

匹配if语句中的preg_matches

I have 2 preg_match in an if statement, and if either of them are true, I want to print_r both of them. But for some reason, only the first preg_match is being matched each time, even though both of them has the same pattern. Why is this happening?

<?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);   
}

?>

Result:

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

Expected Result:

Array ( [0] => how much [1] => how much [2] => much )
Array ( [0] => how much [1] => how much [2] => much )
  • 写回答

1条回答 默认 最新

  • dongzouqie4220 2016-06-26 18:18
    关注

    Explanation:-

    Due to || condition when first one is correct at-once if is executed by ignoring second one. so first one outputs array, but second one gives an Notice: Undefined variable: match2 in D:\xampp\htdocs\abc.php on line 6. It's wierd that you didn't get that error.

    If you want both as output use && instead of || so that both will check and both will print

    So code will be:-

    <?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);   
    }
    
    ?>
    

    Output:-https://eval.in/595814

    Another solution:-

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

    For more learning:- http://php.net/manual/en/language.operators.logical.php

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集