Any questions involving matching text strings to patterns - the pattern is called a "regular expression."
Moderator: General Moderators
SidewinderX
Forum Contributor
Posts: 407 Joined: Fri Jul 16, 2004 9:04 pm
Location: NY
Post
by SidewinderX » Sun Apr 26, 2009 5:09 pm
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
david64
Forum Commoner
Posts: 53 Joined: Sat May 02, 2009 8:12 am
Location: Wales
Post
by david64 » Sat May 02, 2009 8:16 am
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);
prometheuzz
Forum Regular
Posts: 779 Joined: Fri Apr 04, 2008 5:51 am
Post
by prometheuzz » Sat May 02, 2009 9:29 am
@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
Post
by david64 » Sat May 02, 2009 12:26 pm
Thanks for your kind words.
I have got to the stage of being bored with the design now and wanting to change
prometheuzz
Forum Regular
Posts: 779 Joined: Fri Apr 04, 2008 5:51 am
Post
by prometheuzz » Sat May 02, 2009 12:47 pm
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
Post
by SidewinderX » Sat May 02, 2009 4:04 pm
Thanks guys, both solutions work. Is one better than the other?
prometheuzz
Forum Regular
Posts: 779 Joined: Fri Apr 04, 2008 5:51 am
Post
by prometheuzz » Sun May 03, 2009 2:20 am
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:
equals
Code: Select all
'/.+?abc.+?/' // both are made reluctant
while mine will make just one operator reluctant.