2010-03-23 48 views
1

PHP的preg_replace HTML注释我有这样一点PHP代码:空空间

$test = "<!--my comment goes here--> Hello World"; 

现在我想要去除字符串中的整个HTML注释,我知道我需要使用的preg_replace,但现在肯定在正则表达式去那里。 任何人都可以帮忙吗? 感谢

+3

一)重复:http://stackoverflow.com/questions/2475876/php-regexto-remove-comments-but-ignore-occurances-within-strings B)最好不要做与正则表达式。 – 2010-03-23 10:31:47

回答

6
$str=<<<'EOF' 
<!--my comment goes here--> Hello World" 
blah <!-- my another 
comment here --> blah2 
end 
EOF; 

$r=""; 
$s=explode("-->",$str); 
foreach($s as $v){ 
    $m=strpos($v,'<!--'); 
    if($m!==FALSE){ 
    $r.=substr($v,1,$m); 
    } 
} 
$r.=end($s); 
print $r."\n"; 

输出

$ php test.php 
Hello World" 
blah < blah2 
end 

或者,如果你必须的preg_replace,

preg_replace("/<!--.*?-->/ms","",$str); 
2

尝试

preg_replace('~<!--.+?-->~s', '', $html); 
+0

这是整个页面上唯一的好答案。我也加了一个“m”修饰符。 – Damien 2011-10-07 15:20:40

0
<?php 
$test = "<!--my comment goes here--> Hello World"; 
echo preg_replace('/\<.*\>/','',$test); 
?> 

使用全局下面的代码替换:

<?php 
$test = "<!--my comment goes here--> Hello World <!--------welcome-->welcome"; 
echo preg_replace('/\<.*?\>/','',$test); 
?> 
5
preg_replace('/<!--(.*)-->/Uis', '', $html) 

将会删除在$html字符串中的每个HTML注释。希望这可以帮助!

+0

当我使用此代码时,它还会删除显示在2个单独的HTML注释块之间的内容。我认为U修饰符可能会使表达“贪婪”。 而不是试图调整这一点,我用[ghostdog74的回答](https://stackoverflow.com/a/2499137/115432)中的表达,而不是有*。而不是(。*),并使用/ ms而不是/ Uis – strangerstudios 2017-11-28 14:07:15

0

,如果你没有2条与评论之间像那些内容只能工作...

<!--comment--> Im a goner <!--comment--> 

你需要......

//preg_replace('/<!--[^>]*-->/', '', $html); // <- this is incorrect see ridgrunners comments below, you really need ... 
preg_replace('/<!--.*?-->/', '', $html); 

的[^>]匹配任何东西,但>等等至于没有超过匹配>寻找下一个。 我还没有测试phps正则表达式,但它声称是perl正则表达式默认情况下是“贪婪”,并将尽可能匹配。

但是既然你匹配一个专门命名的占位符,你只需要整个字符串,而不是使用str_replace()。

str_replace('<!--my comment goes here-->', $comment, $html); 

而不是在一个文件中替换占位符,只是让它成为一个PHP文件并写出变量。

:)

+2

不可以,'>'是允许的,并且在评论中是完全有效的。在这种情况下,'。*?'lazy-dot-star实际上是更好的表达方式(并且不会像您推断的那样去除“Im im n goner”文本), – ridgerunner 2011-04-19 20:43:56