PHP Developers Network

A community of PHP developers offering assistance, advice, discussion, and friendship.
 
Loading
It is currently Tue Jul 23, 2019 8:14 pm

All times are UTC - 5 hours




Post new topic Reply to topic  [ 2 posts ] 
Author Message
PostPosted: Thu Feb 23, 2012 10:27 am 
Offline
Forum Newbie

Joined: Thu Feb 23, 2012 10:16 am
Posts: 1
Hi everyone,
I have used following PHP regex command:
Syntax: [ Download ] [ Hide ]
$returnValue = preg_replace('/,.*3,/U', ',[replaced],', 'item1,item2,item3,item4,item5');


My expected/wished result is:
Syntax: [ Download ] [ Hide ]
item1,item2,[replaced],item4,item5


The real result is as follows:
Syntax: [ Download ] [ Hide ]
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


Top
 Profile  
 
PostPosted: Thu Feb 23, 2012 5:06 pm 
Offline
Forum Commoner
User avatar

Joined: Thu Dec 15, 2011 2:40 pm
Posts: 85
Location: Nelson, NZ
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:
Syntax: [ Download ] [ Hide ]
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.


Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 2 posts ] 

All times are UTC - 5 hours


Who is online

Users browsing this forum: No registered users and 3 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
Powered by phpBB® Forum Software © phpBB Group