Replace blocks wrapped in HTML comments

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

Moderator: General Moderators

Post Reply
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Replace blocks wrapped in HTML comments

Post by alex.barylski »

I have some HTML source like:

Code: Select all

<!--[START]-->This is some HTML content which needs to be replaced dynamically...is it possible?<!--[FINISH]-->
Here is the simple regex I have constructed thus far:

Code: Select all

$regex = '/<!--\[START\]-->(.|\s)+<--\[FINISH\]-->/';
I can keep the regex simple and assume there is NO whitespace between the comments themselves...only the content inbetween START and FINISH may be subject to whitespace or anything else...which is why I'm confused why my regex doesn't work...even remotely. If I remove the proceeding '+' it matches nothing...if I add it...everything goes bye bye. :(

Can someone please help correct my regex so I can continue with my project. :D

p.s-I'm using preg_replace

Cheers :)
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Re: Replace blocks wrapped in HTML comments

Post by Kieran Huggins »

try:

Code: Select all

$regex = '/<!--\[START\]-->(.*?)<--\[FINISH\]-->/';
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: Replace blocks wrapped in HTML comments

Post by VladSun »

You need a multiline regexp:

Code: Select all

'/<\!--\[START\]-->(.+)<!--\[FINISH\]-->/s'
There are 10 types of people in this world, those who understand binary and those who don't
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Re: Replace blocks wrapped in HTML comments

Post by alex.barylski »

Works like a charm...thanks VladSun and Kieran for your efforts. :)
Post Reply