Remove Whitespace Between HTML Tags Using PHP

/** * Minify specified `HTML` blocks of code. This function removes unnecessary whitespace * that comes as a result keeping your code readable in the back-end. * * This function is meant to be used as an `output buffer` callback paramter. * @see http://php.net/manual/en/function.ob-start.php * * @example { * Before running `ob_start( 'minify_html' )` * ``` * <span> * Some block of text. * </span> * ``` * * After runnning `ob_start( 'minify_html' )` * `<span>Some block of text.</span>` * } * * @param string $html Output callback. * @return mixed */ if ( ! function_exists( 'minify_html' ) ) { function minify_html( $html ) { if ( preg_match( '/(\s){2,}/s', $html ) === 1 ) { return preg_replace( '/(\s){2,}/s', '', $html ); } } }
This function looks for 2 or more consecutive whitespaces between `HTML` tags and removes just the white-space. It's most-effective when needing to remove unnecessary line-breaks that come as a result of keeping code readable during development.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.