使用Regex删除几乎所有的HTML注释


Remove almost all HTML comments using Regex

使用此正则表达式:

preg_replace( '/<!--(?!<!)[^'[>].*?-->/', '', $output )

我可以从我的页面上删除所有HTML注释,除了看起来像这样的内容:

<!--[if IE 6]>
    Special instructions for IE 6 here
<![endif]-->

我如何修改它以排除包含唯一短语(如"batcache")的HTML注释?

因此,HTML注释如下:

<!--
generated 37 seconds ago
generated in 0.978 seconds
served from batcache in 0.004 seconds
expires in 263 seconds
-->

不会被删除。


这个代码似乎起到了作用:

preg_replace( '/<!--(['s'S]*?)-->/', function( $c ) { return ( strpos( $c[1], '<![' ) !== false || strpos( $c[1], 'batcache' ) !== false ) ? $c[0] : ''; }, $output )

这应该替换所有不包含"batcache"的注释。在这两个标签之间进行匹配:<!---->

$result = preg_replace("/<!--((?!batcache)(?!''[endif''])[''s''S])*?-->/", "", $str);

你可以在这里测试。

正如其他用户已经指出的那样,使用regex解析HTML并不总是安全的,但如果您对将要解析的HTML类型有相对的把握,那么它应该按预期工作。如果正则表达式与某些特定用例不匹配,请告诉我。