Skip to content

Instantly share code, notes, and snippets.

@vpadhariya
Last active August 10, 2017 08:21
Show Gist options
  • Save vpadhariya/1513dee4b2230aea3d1d3e771adca0f5 to your computer and use it in GitHub Desktop.
Save vpadhariya/1513dee4b2230aea3d1d3e771adca0f5 to your computer and use it in GitHub Desktop.
PHP Trim html output of a html page
<?php
/**
* Trim output of html
*/
function trim_output($buffer)
{
// Replace key with their values.
$replace = array(
"#<!--.*?-->#s" => "", // strip comments
"#>\s+<#" => ">\n<", // strip excess whitespace
"#\n\s+<#" => "\n<", // strip excess whitespace
'!/\*[^*]*\*+([^/][^*]*\*+)*/!' => '', // Strip css comments
'![ \t]*//.*[ \t]*[\r\n]!' => '', // Removes single line '//' comments, treats blank characters
'~>\s*\n\s*<~' => '><', // Remove extra space between HTML tags
);
// Take keys as search parameter.
$search = array_keys($replace);
// Now replace the buffer (html output)
$buffer = preg_replace($search, $replace, $buffer);
// Return trimmed output buffer
return $buffer;
}
ob_start('trim_output'); // Trim html output (put this code in config of your web application)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment