Skip to content

Instantly share code, notes, and snippets.

@arcollector
Last active June 20, 2016 15:48
Show Gist options
  • Save arcollector/5788757 to your computer and use it in GitHub Desktop.
Save arcollector/5788757 to your computer and use it in GitHub Desktop.
minified html output with php using ob_start
/**
* This snippet minified the html output of your php application, just paste this code
* at the top of your application's entry point
*
* NOTE: <script>, <style>, <pre> and <textarea> tags are not processed by this script, which is a good thing
*
* NOTE: you will need PHP_VERSION >= 5.3 to run this code
*
* NOTE: all the whitespace between tags will be deleted, affecting the visual presentation of your webpage,
* consider this example: <span>Hello, <span>Joe</span></span> -> it will be modified to this ->
* <span>Hello,<span>Joe</span></span>, then on the browser you will see this: Hello,Joe
*
* snippet based on the [minify](https://github.com/mrclay/minify) project
*/
ob_start( function( $buffer ) {
return
// remove ws outside of all elements
preg_replace( '/>(?:\s\s*)?([^<]+)(?:\s\s*)?</s', '>$1<',
// remove ws around all elems excepting script|style|pre|textarea elems
preg_replace(
'/\s+(<\\/?(?!script|style|pre|textarea)\b[^>]*>)/i', '$1',
// trim line start
preg_replace( '/^\s\s*/m', '',
// trim line end
preg_replace( '/\s\s*$/m', '',
// remove HTML comments (not containing IE conditional comments)
preg_replace_callback(
'/<!--([\s\S]*?)-->/',
function( $m ) {
return ( 0 === strpos($m[1], '[' ) || false !== strpos( $m[1], '<![' ) ) ? $m[0] : '';
},
// start point
$buffer
)
)
)
)
)
;
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment