PHP remove whitespace - Use this handy PHP function to remove all whitespace in HTML pages, effectively minifying the HTML page. This will shave off a few kb's on large HTML pages rendered using PHP.
The snippet features are:
The snippet above will remove the whitespace on HTML pages. It uses a PHP function to strip out the whitespace between the HTML elements.
The snippet features are:
- Strip whitespaces after tags, except space
- Strip whitespaces before tags, except space
- Shorten multiple whitespace sequences
- Remove HTML comments
Code:
<?php
function sanitize_output($buffer) {
$search = array(
'/\>[^\S ]+/s', // strip whitespaces after tags, except space
'/[^\S ]+\</s', // strip whitespaces before tags, except space
'/(\s)+/s', // shorten multiple whitespace sequences
'/<!--(.|\s)*?-->/' // Remove HTML comments
);
$replace = array(
'>',
'<',
'\\1',
''
);
$buffer = preg_replace($search, $replace, $buffer);
return $buffer;
}
ob_start("sanitize_output");
?>
The snippet above will remove the whitespace on HTML pages. It uses a PHP function to strip out the whitespace between the HTML elements.