Remove HTML Comments with PHP

By  on  

When it comes to sending content to users, I'm of the belief that less is more.  There's no reason for HTML comments to be sent down to the user -- they simply bloat the payload.  I remove unwanted HTML comments within my WordPress theme, so I thought I'd share the regex that does it:

// Remove unwanted HTML comments
function remove_html_comments($content = '') {
	return preg_replace('/<!--(.|\s)*?-->/', '', $content);
}

That handy function, paired with output buffering, allows me to remove HTML comments from anywhere within the page.  Less load, less cruft for mobile users!

Recent Features

  • By
    Create a CSS Cube

    CSS cubes really showcase what CSS has become over the years, evolving from simple color and dimension directives to a language capable of creating deep, creative visuals.  Add animation and you've got something really neat.  Unfortunately each CSS cube tutorial I've read is a bit...

  • By
    Create a Sheen Logo Effect with CSS

    I was inspired when I first saw Addy Osmani's original ShineTime blog post.  The hover sheen effect is simple but awesome.  When I started my blog redesign, I really wanted to use a sheen effect with my logo.  Using two HTML elements and...

Incredible Demos

  • By
    Check All/None Checkboxes Using MooTools

    There's nothing worse than having to click every checkbox in a list. Why not allow users to click one item and every checkbox becomes checked? Here's how to do just that with MooTools 1.2. The XHTML Note the image with the ucuc ID -- that...

  • By
    jQuery UI DatePicker:  Disable Specified Days

    One project I'm currently working on requires jQuery. The project also features a datepicker for requesting a visit to their location. jQuery UI's DatePicker plugin was the natural choice and it does a really nice job. One challenge I encountered was the...

Discussion

  1. MaxArt

    That would strip out all the comment-like sequences in Javascript code.
    A very rare case indeed, and mixing HTML and Javascript is usually deprecated, but still…
    A fully-fledged HTML-Javascript parser just to prevent this is hardly the effort here.

    Just remember that for backward compatibility for older browsers, script tags’ content are often enclosed in a comment. That would remove the entire script.

    • MaxArt

      I’d like to add that I usually used the sequence [\s\S] instead of the (capturing) group (.|\s). I think it’s faster.

    • You can also do (?:.|\s) to make a group non-capturing. [\s\S] (whitespace or no whitespace) is nonsensical, you could just as well do . (any character).

      David: Why do you do .|\s? As far as I know, . captures all characters, including whitespace.

    • I’ll check it out Fred!

  2. When does this code run?

    The best use I could see for this is a build step, eg you take the template files and them through this on deploy. It feels like a waste of cpu cycles to run something like this per-request?

  3. I like this concept but where/when would you call the function for normal php pages? thx

  4. This is great.

    For my use, I’d prefer this being done from an htaccess file – is this possible at all?

  5. (v)

    what about MSIE conditional comments? ;-)

    my code is like:

    ...
    return preg_replace('/<!--(?!\s*(?:\[if [^\]]+]|))(?:(?!-->).)*-->/s', '', $content);

    • Awesome point, love this — I’ll check it out and if it works I’ll update my post!

    • I tried this but it didn’t work :/ No comments were stripped at all.

    • Hi David, (V), the following mix of your snippets workes for me

      $data = preg_replace(‘//’, ”, $data);

  6. It depends on our framework, it should have a pipeline to minimize the html before sending it into client :D
    But thanks for your useful snippet :)

  7. Wouldn’t this alter IE conditional comments?

  8. Hi David, (V), the following mix of your snippets workes for me

    $data = preg_replace(‘//’, ”, $data);

    2nd try, I used pre but the code was removed …

  9. Hi David, (V), the following mix of your snippets workes for me

    http://pastebin.com/bfzWVFUi

    3rd try, I used pre but the code was removed … please delete my two previous comments

  10. Mike Smith

    I added this code to my functions.php file, however, visitors can still post strong html tags and images on my blog :(

  11. good concept and thanks for that

  12. spongeBob

    Nice approach. But it would be more believable if I you also removed html comments on this page. :) But I liked the regex.

  13. Jack

    Why even bother with putting in HTML comments at all? Since commenting is supposed to be for future developers eyes who will be reading the actual code I just comment in php and then don’t have to worry about comments passed into html.

  14. Full strip function

    function html2txt($document){
    $search = array('@]*?>.*?@si',  // Strip out javascript
                   '@<[\/\!]*?[^]*?>@si',            // Strip out HTML tags
                   '@]*?>.*?@siU',    // Strip style tags properly
                   '@@'         // Strip multi-line comments including CDATA
    );
    $text = preg_replace($search, '', $document);
    return $text;
    } 
    
  15. JoeB

    This crashes horribly if the comment inside the tag is very large.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!