2016-06-26 6 views
0

if文に2つのpreg_matchがあり、いずれかが真である場合は、両方ともprint_rしたいです。しかし、何らかの理由で、最初のpreg_matchだけが、同じパターンを持っていても毎回一致しています。なぜこうなった?if文のpreg_matchesの両方を一致させる

<?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) 
+0

http://php.net/manual/en/language.operators.logical.php – axiac

答えて

3

説明: -

により||条件への最初のものはアットワンスであれば正しいとき元です第2のものを無視することによって生起される。最初のものは配列を出力しますが、2番目のものは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

別溶液: -

詳細: - http://php.net/manual/en/language.operators.logical.php

関連する問題