使用正则表达式和php删除除Internet Explorer注释以外的所有html注释 [英] Removing all html comments except internet explorer comments using regex and php

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

问题描述

我是新来的正则表达式,但需要一个能够移除所有HTML注释(<! - here - > )但不包含Internet Explorer注释的代码<! - [if IE 7]> here<![endif] - > )。我有这样的代码:
369

 <?php 
function stripTags($ text,$ tags )
{
//替换Internet Explorer注释标记,以免它们被剥离

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

//替换所有正常的html注释
$ text = preg_replace('/<! - (。| \\\
)*? - > / g',' ',$& text);


//将Internet Explorer评论标记返回到其原始位置

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

返回$ text;
}
?>

请提供任何帮助。

解决方案

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

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

请参阅这里在线



更新:前瞻断言是一个非捕获(零长度)表达式(就像检查单词边界的achor \b)一样,这意味着它不会消耗字符,它会检查表达式是否匹配,如果是,则会在表达式之前的字符之后继续。否定的是检查没有下面的表达式。我最好链接到手册,这里是 PerlReTut 。应该在这一点上与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注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆