簡體   English   中英

PHP刪除所有HTML,但保留注釋

[英]PHP remove all html but comments

我如何刪除所有HTML輸入內容但包含注釋? 例如:此<html><body><!-- hello paragraph --><p>hello</p></body></html>會變成這樣:此<!-- hello paragraph -->

我該怎么做? 謝謝!

編輯:我知道您可以使用正則表達式執行類似的操作,但是我不知道如何做。

我將使用以下方法提取所有注釋,而不是替換HTML:

preg_match_all('#(<!--.*?-->)#s', '<html><body><!-- hello paragraph --><p>hello</p></body></html>', $m);

確實確實有點復雜,但是可以使用正則表達式:

$text = preg_replace('~<(?!!--)/?\w[^>]*(?<!--)>~', "", $text);

這適用於您的示例,但可能對其他人失敗。 有趣的是,它還從注釋中刪除了HTML標簽。

$regex = '~
    <             # opening html bracket
    (?!!--)       # negative assertion, no "!--" may follow
    /?\w          # tags must start with letter or optional /
    [^>]*         # matches html tag innards
    (?<!--)       # lookbehind assertion, no "--" before closing >
    >             # closing bracket
 ~x'
$foo="<html><body><!-- hello paragraph --><p>hello</p></body></html>";
preg_match('/(\<|<)!--(\s*.*?\s*)--(\>|>)/m',$foo,$result);
print_r($result);

暫無
暫無

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

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