Forum Moderators: coopster

Message Too Old, No Replies

PHP Regex help

need help with regex

         

netfiends

10:43 pm on May 6, 2005 (gmt 0)

10+ Year Member



I'm not good with regex, I've search for a couple hours and couldn't find it so here I am. I'm looking for a regex that finds and replaces stuff between (2) html comments. I.e.

<!-- START comment --> random text... <!-- END comment -->

Anyone know how to do this?

Longhaired Genius

11:15 pm on May 6, 2005 (gmt 0)

10+ Year Member



$text = preg_replace('/(\<\!\-\-\ START\ comment\ \-\-\>\ ).*?(\ \<\!\-\-\ END\ comment\ \-\-\>)/', '\\1new text\\2', $text);

or

$text = preg_replace('/(\<\!\-\-\sSTART\scomment\s\-\-\>\s).*?(\s\<\!\-\-\sEND\scomment\s\-\-\>)/', '\\1new text\\2', $text);

Welcome to Webmaster World.

coopster

11:41 am on May 7, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



A trick with all those special characters is to use PHP's preg_quote() [php.net] function:
$string = '<!-- START comment --> random text... <!-- END comment -->'; 
$cb = preg_quote('<!--'); // comment begin
$ce = preg_quote('-->'); // comment end
print preg_replace("/($cb.*$ce).*($cb.*$ce)/Us", "$1My replacement text$2", $string);

The "U" modifier makes it "Ungreedy" so it won't try to grab everything in one shot (in case there is more than one comment in the string). And the "s" modifier allows it to read multiline input strings (newlines).

netfiends

4:16 pm on May 7, 2005 (gmt 0)

10+ Year Member



I'm confused on why you have: $1My replacement text$2. I don't get why you have the $ and #'s following...

Longhaired Genius

5:35 pm on May 7, 2005 (gmt 0)

10+ Year Member



The $1 and $2 (or \\1 and \\2 in my code) are backreferences, which replace the comments around your new text. In this context, they are part of the regular-expression syntax and should not be confused with php variables.