Bill D
Bill D

Reputation: 31

PHP preg_replace bug?

I'm using the following regex's:

$sEmailHTML = preg_replace ("/<\!-- +(\\[[\"a-zA-Z_]+\\]) +-->/U", "\\1", $sEmailHTML);
$sEmailHTML = preg_replace ("/\\[\"(.+)\"\\]/U", "\\1", $sEmailHTML);

on this text:

["Text:"]
<!-- ["Click this to authenticate"] --> <!-- [authlink] -->
<!-- ["Dear"] --> <!-- [firstname] --><!-- [":"] -->

and it's giving me this result: (having also replaced [authlink] and [firstname])

Text:
<!-- Click this to authenticate --> <a href="http://www.mydomain.tld/auth.php?jj=100&aa=SOMEVALUE&end">http://www.mydomain.tld/auth.php?jj=100&aa=SOMEVALUE&end</a>
Dear John<!-- : -->

when it should be giving this:

Text:
Click this to authenticate <a href="http://www.mydomain.tld/auth.php?jj=100&aa=SOMEVALUE&end">http://www.mydomain.tld/auth.php?jj=100&aa=SOMEVALUE&end</a>
Dear John:

I can't figure out why it's not removing all of the HTML comment tags. It also doesn't work if I execute the comment remover regex twice. So it's either a bug or I'm missing something. (PHP 5.2.17)

THANKS. I wasn't thinking. Changed to and working:

$sEmailHTML = preg_replace ("/<!-- +(\\[[a-zA-Z_]+\\]) +-->/U", "\\1", $sEmailHTML);
$sEmailHTML = preg_replace ("/<!-- +(\\[\".+\"\\]) +-->/U", "\\1", $sEmailHTML);
$sEmailHTML = preg_replace ("/\\[\"(.+)\"\\]/U", "\\1", $sEmailHTML);

Upvotes: 1

Views: 847

Answers (1)

codaddict
codaddict

Reputation: 455142

This is happening because the text

"Click this to authenticate"

has spaces in them and your regex:

"/<\!-- +(\\[[\"a-zA-Z_]+\\]) +-->/U"

does not match spaces. Also, to match a literal [, use \[, not \\[.

Change it to:

"/<!-- +(\[[\"a-zA-Z_ ]+\]) +-->/U"
                     ^

See it

Upvotes: 3

Related Questions