Skip to content

Instantly share code, notes, and snippets.

@k4zuki02h4t4
Last active August 29, 2015 14:13
Show Gist options
  • Save k4zuki02h4t4/9564b2f328408d082937 to your computer and use it in GitHub Desktop.
Save k4zuki02h4t4/9564b2f328408d082937 to your computer and use it in GitHub Desktop.
Minify the HTML that is output from WordPress.
/**
* Replace the buffer.
*
* @link http://insnvlovn.blogspot.jp/2010/04/php-obstart.html
* @param buffer $buffer
* @return buffer $buffer
*/
function buffer_replace( $buffer ) {
$pattern = array( "/(?:\r\n)|[\r\n]/", "/[\\x00-\\x09\\x0b-\\x1f]/" );
$replace = array( "\n", " " );
$buffer = preg_replace( $pattern, $replace, $buffer );
unset( $pattern, $replace );
$pattern = array( '/<!--(.*?)-->/', '/\n/', '/\t/', '/[ \s]+/umi' );
$replace = array( '', '', '', ' ' );
$i = 0;
$tmpName = "__TMP__";
do {
if ( !isset( $GLOBALS[$tmpName . $i] ) ) {
$tmpName .= $i;
break;
}
if ($i > 10) {
$tmpName .= md5( mt_rand() ) . md5( mt_rand() );
break;
}
$i++;
} while ( true );
$GLOBALS[$tmpName] = array();
$buffer = preg_replace_callback( "/<(pre|s(?:cript|tyle)|xmp)(?:\s*|(?:\s+[^>]+))>(.*?)<\/\\1\s*>/is", create_function( '$matches', '$tmp =& $GLOBALS["' . $tmpName . '"];' . 'if ($matches[2] === "") { return $matches[0]; }' . '$tmp[] = $matches[0];' . 'return "<\\x00," . count( $tmp ) . ",\\x01>";'), $buffer );
$buffer = preg_replace( $pattern, $replace, $buffer );
$buffer = preg_replace_callback( "/<\\x00,(\d+),\\x01>/", create_function( '$matches', '$tmp =& $GLOBALS["' . $tmpName . '"];' . 'return $tmp[$matches[1] - 1];' ), $buffer );
return $buffer;
}
/**
* Turn on output buffering.
*
* @return boolean
*/
function buffer_ob_start() {
ob_start( 'buffer_replace' );
}
add_filter( 'after_setup_theme', 'buffer_ob_start' );
/**
* Flush (send) the output buffer and turn off output buffering.
*
* @return boolean
*/
function buffer_ob_end_flush() {
ob_end_flush();
}
add_filter( 'shutdown', 'buffer_ob_end_flush', 0 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment