|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2010-01-30 16:58 UTC] harrrrpo at gmail dot com
Description:
------------
in preg_match , when optional sub-patterns (using ? or {0,n} ) are the last sub-patterns and empty (e.g. not matched) they are ignored in $matches array
this behavior is inconsistent with preg_match_all , and with the case when the empty optional sub-pattern isn't the last one
Reproduce code:
---------------
$str="1";
preg_match("#\d(\d)?#",$str,$mt);
var_dump($mt);
Expected result:
----------------
array(2) {
[0]=>
string(1) "1"
[1]=>
string(0) ""
}
(the string(0) "" does appear on all cases with preg_match_all , and with preg_match , when there is any additional sub-patterns after it)
Actual result:
--------------
array(1) {
[0]=>
string(1) "1"
}
(the value of sub-pattern vanished)
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Tue Oct 28 00:00:02 2025 UTC |
Delving into a fix for this bug, I found that it's not limited to last optional groups but to any last groups. In fact, the following: <code> $regex = '(?|(Sat)ur(day)|Sun(day)?)'; preg_match("@$regex@", 'Saturday', $matches); print_r($matches); preg_match("@$regex@", 'Sunday', $matches); print_r($matches); preg_match("@$regex@", 'Sun', $matches); print_r($matches); </code> prints: Array ( [0] => Saturday [1] => Sat [2] => day ) Array ( [0] => Sunday [1] => day ) Array ( [0] => Sun ) While it should print: Array ( [0] => Saturday [1] => Sat [2] => day ) Array ( [0] => Sunday [1] => day [2] => ) Array ( [0] => Sun [1] => [2] => )I was about to file a duplicate defect when I found this one. Yes I agree, very aggravating that it's not at least in the documentation. For reference these were gonna be my EXPECTED RESULTS php > preg_match('/(a)(b)(c)*/', 'ab', $matches); php > var_dump($matches); php shell code:1: array(3) { [0] => string(2) "ab" [1] => string(1) "a" [2] => string(1) "b" [3] => string(0) "" } php > preg_match('/(a)(b)(c)*/', 'ab', $matches, PREG_UNMATCHED_AS_NULL); php > var_dump($matches); php shell code:1: array(3) { [0] => string(2) "ab" [1] => string(1) "a" [2] => string(1) "b" [3] => NULL } php >