RsD0p9BK
12/23/2015 - 11:00 AM

minified.html.output.php

// 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 
						)
					)
				)
			)
		)
	;
} );

// https://gist.github.com/arcollector/5788757