Explorer注释以外的所有html注释

Explorer注释以外的所有html注释

本文介绍了使用正则表达式和php删除除Internet Explorer注释以外的所有html注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的正则表达式,但需要一个能够移除所有HTML注释(

为什么不只是使用负向前视来确保注释不以开头[if ?这更容易阅读,评论也可以包含 [和] 。

 <! - (?! \ [if]。*? - > 



更新:前瞻断言是一个非捕获(零长度)表达式(就像检查单词边界的achor \b)一样,这意味着它不会消耗字符,它会检查表达式是否匹配,如果是,则会在表达式之前的字符之后继续。否定的是检查没有下面的表达式。我最好链接到手册,这里是。应该在这一点上与php没有区别。


I am new in regex but need a code that would remove all html comments (<!-- here -->) but not internet explorer comments like (<!--[if IE 7]> here <![endif]-->). I have this code: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;
}
?>

Any help please.

解决方案

Why not just use a negative lookahead to ensure that the comment does not start with [if? that is easier to read and the comment can contain also [ and ].

<!--(?!\[if).*?-->

See here online

Update: A lookahead assertion is a non capturing(zero length) expression (like an achor \b that checks for a word boundary), that means it does not consum the characters, it checks if the expression is matching and if yes it continues right after the character before the expression. The negative one is checking that there isn't the expression following. I better link to a manual, here is the PerlReTut. Should be at that point no difference to php.

这篇关于使用正则表达式和php删除除Internet Explorer注释以外的所有html注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 22:14