使用 Regex 删除几乎所有 HTML 评论

Remove almost all HTML comments using Regex

使用这个正则表达式:

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

我可以从我的页面中删除所有 HTML 评论,但看起来像这样的评论除外:

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

我如何修改它以同时排除 HTML 包含独特短语的评论,例如 "batcache"?

所以,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);

你可以测试一下here

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