How to remove html comment from source?

Here’s a quick way to remove all comments using output buffering and preg_replace. We hook in before WordPress starts outputting the HTML to start the buffer. Then we hook in after WordPress stops outputting the HTML to get the buffer and strip the HTML comment tags from the content.

This code would ideally be in it’s own plugin. But it could be in your functions.php if you’re really adverse to adding more plugins.

namespace StackExchange\WordPress;

//* Start output buffering
function startOutputBuffer() {
  ob_start();
}

//* Print the output buffer
function stopOutputBuffer() {
  $html = ob_get_clean();
  echo strip_html_comments( $html );
}

//* See note for attribution of this code
function strip_html_comments( string $html ) : string {
  return preg_replace('/<!--(.*)-->/Uis', '', $html);
}

//* Add action before WordPress starts outputting content to start buffer
add_action( 'wp', __NAMESPACE__ . '\startOutputBuffer' );

//* Add action after WordPress stops outputting content to stop buffer
add_action( 'shutdown', __NAMESPACE__ . '\stopOutputBuffer' );

Note: Regex from this StackOverflow answer by Benoit Villière.

Leave a Comment

tech