2012-05-03 71 views
1

我使用下面的正则表达式的:PHP preg_replace错误?

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

在这样的文字:

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

和它给了我这样的结果:(已还更换[authlink]和[名字])

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<!-- : --> 

当它应该给这个:

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: 

我不明白为什么它不会删除所有的HTML注释标记。 如果我执行两次注释去除器正则表达式,它也不起作用。 因此,这可能是一个错误,或者我错过了一些东西。 (PHP 5.2.17)

谢谢。我没在想。改为和工作:

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

为什么''逃脱?为什么有两个方括号'[['在评论文本块的开头? – Jon

回答

3

发生这种情况,因为文本

"Click this to authenticate" 

有空间在他们和你的正则表达式:

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

不匹配的空间。此外,要与文字[相匹配,请使用\[,而不是\\[

将其更改为:

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

See it