Page 1 of 1

Ungreedy still too greedy

Posted: Thu Feb 23, 2012 9:27 am
by janosh7
Hi everyone,
I have used following PHP regex command:

Code: Select all

$returnValue = preg_replace('/,.*3,/U', ',[replaced],', 'item1,item2,item3,item4,item5');
My expected/wished result is:

Code: Select all

item1,item2,[replaced],item4,item5
The real result is as follows:

Code: Select all

item1,[replaced],item4,item5
Therefore the replacement was too greedy, because it also replaced item2, instead of only replacing item3. Why is this? And how to rewrite the regex pattern in order to only replace item3?

Thanks and kind regards,
janosh

Re: Ungreedy still too greedy

Posted: Thu Feb 23, 2012 4:06 pm
by ragax
Hi janosh7,

It's not a greediness problem. Your regex matches the first comma, then lazily matches everything, expanding as needed until it finds a 3.
This means it eats up item 2 and item 3.

This fixes it:

Code: Select all

echo preg_replace('~,[^,]+3,~', ',[replaced],', 'item1,item2,item3,item4,item5');
Output: item1,item2,[replaced],item4,item5
It matches a comma, than any number of characters that are not a comma, then a 3 and a comma.

On my tut you can read the "degrees of greed" page for more details about greedy and lazy matching.
Let me know if you have any questions! :)

Wishing you a fun day.