Re: preg_match too greedy
| From: | Daniel Kolbo | Date: | Wed, 29 Jul 2009 23:48:42 +0000 |
| Subject: | Re: preg_match too greedy | ||
| References: | 1 2 3 4 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-296042@lists.php.net to get a copy of this message | ||
Jim Lucas wrote:
> Ben Dunlap wrote:
>> Jim Lucas wrote:
>>>> I expected 'no match' but get 'match'.
>> [8<]
>>> cut/paste your code and it works for me.
>> Works for me as well. I get 'no match' from PHP 5.1.2, 5.2.6, and 5.2.8. What
>> version do you have?
>
> PHP 5.2.5 with Suhosin-Patch 0.9.6.2 (cli) (built: Mar 11 2008 13:08:50)
> Copyright (c) 1997-2007 The PHP Group
> Zend Engine v2.2.0, Copyright (c) 1998-2007 Zend Technologies
> with Suhosin v0.9.20, Copyright (c) 2002-2006, by Hardened-PHP Project
>
>
>> If I might suggest a couple of simplifications that would make it easier to
>> follow/troubleshoot:
>>
>>>> $url = '/foo(/)?';
>> I don't think you need parentheses around your second forward-slash. If you had
>> multiple characters that were optional you'd want to group them in parentheses,
>> but here I think it just makes the regex harder to read.
>>
>>>> echo (preg_match($pattern, $test) != false)
>> The " != false " here is redundant. Combined with the ternary operator, the
>> logical switchbacks make me a little dizzy (especially this close to lunchtime).
>>
>> Ben
>>
>
>
>
code works (no match) for me too on php 5.2.6 build date May 2 2008
18:01:20 with dumbdows NT.
preg_match fails but for a reason other than what I think you may be
expecting. It fails b/c of the first forwards slash in $url. The regex
engine doesn't even get past the second character let alone reaching the
end of line anchor.
Also, your code works (no match) with this first forward slash removed:
$url = 'foo(/)?'
This time preg_match fails due to the end of line anchor.
hth
dK
`