2011-03-18 95 views
0

我將如何刪除所有的html輸入,但評論?例如: 這<html><body><!-- hello paragraph --><p>hello</p></body></html> 會變成這樣:此<!-- hello paragraph -->PHP刪除所有的HTML,但評論

我會怎麼做呢?謝謝!

編輯:我知道你可以用正則表達式這樣做,但我不知道如何。

回答

1

而不是取代HTML的,我想用提取所有評論:

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

我相信部份的做法會比試圖確定非評論更穩健。它也不會有註釋內部的HTML標籤被堵塞或刪除的缺點。 – thomasrutter 2011-03-18 03:35:28

0

這確實有點複雜,但用正則表達式是可行的:

$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' 
0
$foo="<html><body><!-- hello paragraph --><p>hello</p></body></html>"; 
preg_match('/(\<|<)!--(\s*.*?\s*)--(\>|>)/m',$foo,$result); 
print_r($result);