【问题标题】:Removing all html comments except internet explorer comments using regex and php使用正则表达式和 php 删除除 Internet Explorer 注释之外的所有 html 注释
【发布时间】:2011-08-17 15:49:05
【问题描述】:

我是正则表达式的新手,但需要一个代码来删除所有 html cmets (<!-- here -->),但不能删除 Internet Explorer cmets (<!--[if IE 7]> here <![endif]-->)。我有这个代码: 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;
}
?>

请帮忙。

【问题讨论】:

标签: php regex html


【解决方案1】:

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

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

See here online

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

【讨论】:

  • 请您解释一下负面展望是如何运作的?谢谢
  • @Abhishek,我添加了一些解释和答案链接。
  • 在线的rubular很棒,它使正则表达式变得不那么棘手。非常感谢您的链接
  • 这太棒了 - 简短而甜蜜 - 正是我想要的。
【解决方案2】:

如果你知道页面上没有 HTML cmets 使用 [ 和 ] 字符,除了 if 条件,你可以使用:

preg_replace("/&lt;!--([^\[\]]*)--&gt;/", "", $text);

【讨论】:

  • @Juma 很高兴,很高兴它有帮助。
【解决方案3】:

试试这个
\&lt;!--[\(\.\|\\\w\)\*\?\d\-\+\}\{]+--&gt;

【讨论】:

    猜你喜欢
    • 2011-05-02
    • 2010-11-08
    • 1970-01-01
    • 2011-08-04
    • 1970-01-01
    • 2019-08-28
    • 1970-01-01
    • 2011-01-28
    相关资源
    最近更新 更多