greedy quantifier issue?

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
SidewinderX
Forum Contributor
Posts: 407
Joined: Fri Jul 16, 2004 9:04 pm
Location: NY

greedy quantifier issue?

Post by SidewinderX »

I am trying to remove comments from a piece of code. For example:

Code: Select all

/* Header */
This is my header
/* Footer */
This is my footer
/* EOF */

would become

Code: Select all

This is my header
This is my footer
I tried

Code: Select all

$content = preg_replace("/\/\*.*\*\//", "", $content);

This *works* but it matches the /* before Header and the last */ before EOF which causes the entire file to be replaced with nothing. How can I craft my expression to get the results I expect?


Thanks,
John
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: greedy quantifier issue?

Post by prometheuzz »

Try:

Code: Select all

$content = preg_replace("@/\*.*?\*/@s", "", $content);
david64
Forum Commoner
Posts: 53
Joined: Sat May 02, 2009 8:12 am
Location: Wales

Re: greedy quantifier issue?

Post by david64 »

By default PRCE, which powers the preg functions is set to greedy. You can turn this off using the U modifer like so:

Code: Select all

$content = preg_replace('/expression/U', '', $content);
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: greedy quantifier issue?

Post by prometheuzz »

@david64

Impressive website you have. Nice and clean, I like it a lot!
david64
Forum Commoner
Posts: 53
Joined: Sat May 02, 2009 8:12 am
Location: Wales

Re: greedy quantifier issue?

Post by david64 »

Thanks for your kind words.

I have got to the stage of being bored with the design now and wanting to change :|
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: greedy quantifier issue?

Post by prometheuzz »

david64 wrote:Thanks for your kind words.

I have got to the stage of being bored with the design now and wanting to change :|
Snob!
;)
SidewinderX
Forum Contributor
Posts: 407
Joined: Fri Jul 16, 2004 9:04 pm
Location: NY

Re: greedy quantifier issue?

Post by SidewinderX »

Thanks guys, both solutions work. Is one better than the other?
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: greedy quantifier issue?

Post by prometheuzz »

SidewinderX wrote:Thanks guys, both solutions work.
Glad to hear it.
SidewinderX wrote:Is one better than the other?
No, not really. Davids proposal will make all greedy operators in the regex reluctant. So this regex:

Code: Select all

'/.+abc.+/U'
equals

Code: Select all

'/.+?abc.+?/' // both are made reluctant
while mine will make just one operator reluctant.
Post Reply