简体   繁体   中英

PHP remove all html but comments

How would I remove all of a an html input but comments? For example: This <html><body><!-- hello paragraph --><p>hello</p></body></html> Would turn into this: This <!-- hello paragraph -->

How would I do this? Thanks!

Edit: I know you can do stuff like this with regular expressions, But I don't know how.

我将使用以下方法提取所有注释,而不是替换HTML:

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

That's indeed a bit more complex, but doable with regular expressions:

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

This works on your example, but can fail for others. Amusingly it also removes HTML tags from within comments.

$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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM