使用正则表达式和php删除除Internet Explorer注释之外的所有html注释

Jum*_*nce 4 html php regex

我是正则表达式的新手,但需要一个能删除所有html注释(<!-- here -->)的代码,但不需要像(<!--[if IE 7]> here <![endif]-->)这样的Internet Explorer注释.我有这个代码:369

<?php
function stripTags($text, $tags)
{
  // replace the internet explorer comments tags so they do not get stripped  

  $text = preg_replace("<!--[if IE7] (.*?) <![endif]-->", "#?#", $text);

  // replace all the normal html comments
  $text =preg_replace('/<!--(.|\n)*?-->/g', '', $&text);


  // return internet explorer comments tags to their origial place

  $text = preg_replace("@#\?#@", "<!--[if IE7] (.*?) <![endif]-->", $text);

  return $text;
}
?>
Run Code Online (Sandbox Code Playgroud)

请帮忙.

ste*_*ema 9

为什么不使用否定前瞻来确保评论不以[if?开头?这更容易阅读,评论也可以包含[].

<!--(?!\[if).*?-->
Run Code Online (Sandbox Code Playgroud)

在线查看

更新:前瞻断言是一个非捕获(零长度)表达式(如检查单词边界的achor\b),这意味着它不会消耗字符,它会检查表达式是否匹配,如果是,则继续正确在表达之前的字符之后.否定的是检查下面没有表达式.我更好地链接到手册,这里是PerlReTut.应该在那一点上没有差异到PHP.