Last active
August 10, 2017 08:21
-
-
Save vpadhariya/1513dee4b2230aea3d1d3e771adca0f5 to your computer and use it in GitHub Desktop.
PHP Trim html output of a html page
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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