Skip to content

Instantly share code, notes, and snippets.

@kazimolmez
Created April 20, 2018 18:51
Show Gist options
  • Save kazimolmez/148bc94a3d6b2dba06a28139e26e9cdb to your computer and use it in GitHub Desktop.
Save kazimolmez/148bc94a3d6b2dba06a28139e26e9cdb to your computer and use it in GitHub Desktop.
PHP HTML Output Compressor
<?php
ob_start("html_compress");
ob_implicit_flush(1);
function html_compress($html){
$html = preg_replace('/<!-(.*)->/Uis', '', $html);
$html = preg_replace('/[\r\n\t\s]+/s', ' ', $html);
$html = preg_replace('#/\*.*?\*/#', ' ', $html);
$html = preg_replace('/^\s+/', ' ', $html);
$html = preg_replace('/ +/', ' ', $html);
$html = preg_replace('/> +</', '><', $html);
$html = preg_replace('/[[:blank:]]+/', ' ', $html);
$html = preg_replace('/<!--[if IE]>/', $html, $html);
$html = preg_replace('/<![endif]-->/', $html, $html);
$html = preg_replace_callback("/(&#[0-9]+;)/", function($m){
return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES");
}, $html);
$html = preg_replace_callback("/([a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})/", function($m){
return encode2($m[1]);
}, $html);
$HTTP_ACCEPT_ENCODING = $_SERVER["HTTP_ACCEPT_ENCODING"];
if(headers_sent()) {
$encoding = false;
}elseif( strpos($HTTP_ACCEPT_ENCODING, 'x-gzip') !== false ) {
$encoding = 'x-gzip';
}elseif( strpos($HTTP_ACCEPT_ENCODING,'gzip') !== false ) {
$encoding = 'gzip';
}else{
$encoding = false;
}
return $html;
ob_end_clean();
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment