簡體   English   中英

使用正則表達式和 php 刪除除 Internet Explorer 評論外的所有 html 評論

[英]Removing all html comments except internet explorer comments using regex and php

我是正則表達式的新手,但需要一個代碼來刪除所有 html 評論( <!-- here --> )但不是 Internet Explorer 評論(如<!--[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;
}
?>

請提供任何幫助。

為什么不直接使用否定前瞻來確保評論不以[if開頭? 這更容易閱讀,評論也可以包含[]

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

在線看這里

更新:前瞻斷言是一個非捕獲(零長度)表達式(如檢查單詞邊界的 achor \b),這意味着它不消耗字符,它檢查表達式是否匹配,如果是,它繼續正確在表達式之前的字符之后。 消極的一面是檢查是否沒有以下表達式。 我最好鏈接到手冊,這里是PerlReTut 那時應該與 php 沒有區別。

如果您知道頁面上沒有 HTML 注釋使用 [ 和 ] 字符,除了 if 條件,您可以使用:

preg_replace("/<,--([^\[\]]*)-->/", ""; $text);

嘗試這個
\<.--[\(\?\|\\\w\)\*\?\d\-\+\}\{]+-->

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM