note 17519 added to function.preg-match
| From: | mike at php2 dot chek dot com | Date: | Wed, 12 Dec 2001 18:02:44 +0000 |
| Subject: | note 17519 added to function.preg-match | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-22548@lists.php.net to get a copy of this message | ||
if you use preg_match in a loop where you expect only one match (on each string comparison), and
wish to use all the matches collected in ($matches in the above example) do NOT assume that
preg_match() increments this array and continues populating it - this is not the case. preg_match()
does not use 'array_push' (or equivalent) to populate this array - it just continually
writes to $matches[0]. so even if you get a match somewhere in the loop, if the last item you
compare to does not match, the array will end up null.<br>
as a workaround, use a comparator in your loop that checks to see if $matches[0] has a value, and if
so, pushes that value onto another array:<br>
/* this routine reads a directory ($dir2check) and compares
* each item to a regexp, then harvests the results into
* the array $matcharr. as a bonus, the value of $disp
* will be equal to the number of matches found in the loop */
$dr = dir($dir2check);
$matcharr = array();
while(($itm=$dr->read())) { //
// this is a simple regexp that will match any file that has
// 8 characters, then a dot, then 3 digits i.e. abcd_123.456
$disp += preg_match("/^\w{8}\.\d{3}$/i", $itm, $matches);
// if the $matches array above has any values in it
if ($matches[0]) { //
// we push those values onto the array $matcharr
array_push($matcharr, $matches[0]);
}
}
$dr->close();
/* you now have 2 results:
* $disp is equal to the number of matches found,
* $matcharr is an array of all matches found in the loop */<br>
you could also use this to create a multi-dimensional array if you expect there to be more than one
match between the regexp and the string. in that case, don't use array_push($matcharr,
$matches[0]); instead use array_push($matcharr, $matches);<br>
then each element of $matcharr will be an array of matches.<br>
--
http://www.php.net/manual/en/function.preg-match.php
http://master.php.net/manage/user-notes.php?action=edit+17519
http://master.php.net/manage/user-notes.php?action=delete+17519
http://master.php.net/manage/user-notes.php?action=reject+17519