note 104378 added to function.preg-match
| From: | cappuccino dot e dot cornetto at gmail dot com | Date: | Sun, 12 Jun 2011 13:49:36 +0000 |
| Subject: | note 104378 added to function.preg-match | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-180451@lists.php.net to get a copy of this message | ||
Please disregard my previous note (http://php.net/manual/en/function.preg-match.php#104376) because
the value of the $missing variable was wrong.
---
There is a small bug in this function that you should be aware of because they're not going to
fix it; see http://bugs.php.net/bug.php?id=50887
My fix follows.
<?php
function preg_match_ok( $pattern, $subject, array &$matches = NULL, $flags = NULL, $offset =
NULL )
{
$result = preg_match($pattern, $subject, $m, $flags, $offset);
if (is_null($matches))
{
return $result;
}
$matches = $m;
if ($result)
{
$pattern = preg_replace('/\\\\./', '%', $pattern); // disable escaped
characters
$pattern = preg_replace('/\[[^\]]*\]/', '%', $pattern); // disable
enumerations
$find_named_groups =
'/\(\?P?(?:(?:<([^>]+)>)|(?:\'([^\']+)\'))/';
$named_groups_count = preg_match_all($find_named_groups, $pattern, $named_groups, PREG_SET_ORDER |
PREG_OFFSET_CAPTURE);
$find_index_groups = '/\((?!\?)/';
$index_groups_count = preg_match_all($find_index_groups, $pattern, $index_groups, PREG_SET_ORDER |
PREG_OFFSET_CAPTURE);
$groups_count = $index_groups_count + $named_groups_count;
if ($groups_count == count($matches)) //it should be $groups_count == count($matches) - 1, see http://bugs.php.net/bug.php?id=50887
{
$missing = $flags == PREG_OFFSET_CAPTURE ? array('', -1) : '';
$last_group_offset['named'] = -1;
if ($named_groups_count)
{
$last_named_group = array_pop(array_pop($named_groups));
$last_group_offset['named'] = $last_named_group[1];
}
$last_group_offset['index'] = -1;
if ($index_groups_count)
{
$last_index_group = array_pop(array_pop($index_groups));
$last_group_offset['index'] = $last_index_group[1];
}
$last_group_type = array_search(max($last_group_offset), $last_group_offset);
if ('named' == $last_group_type)
{
$matches[$last_named_group[0]] = $missing;
}
$matches[] = $missing;
}
}
return $result;
}
?>
----
Server IP: 69.147.83.197
Probable Submitter: 80.56.168.144
----
Manual Page -- http://www.php.net/manual/en/function.preg-match.php
Edit -- https://master.php.net/note/edit/104378
Del: integrated -- https://master.php.net/note/delete/104378/integrated
Del: useless -- https://master.php.net/note/delete/104378/useless
Del: bad code -- https://master.php.net/note/delete/104378/bad+code
Del: spam -- https://master.php.net/note/delete/104378/spam
Del: non-english -- https://master.php.net/note/delete/104378/non-english
Del: in docs -- https://master.php.net/note/delete/104378/in+docs
Del: other reasons-- https://master.php.net/note/delete/104378
Reject -- https://master.php.net/note/reject/104378
Search -- https://master.php.net/manage/user-notes.php