Skip to content

Instantly share code, notes, and snippets.

@gaffling
Last active February 7, 2020 07:34
Show Gist options
  • Save gaffling/68bcaf0a432814723f317ffd943138c2 to your computer and use it in GitHub Desktop.
Save gaffling/68bcaf0a432814723f317ffd943138c2 to your computer and use it in GitHub Desktop.
[HTML Compress] This function can be used to minify HTML #php #function #HTMLminify
<?php
/* ----------------------------------------------------------------------------------- */
/* [HTML Compress] This function can be used to minify HTML #php #function #HTMLminify */
/* ----------------------------------------------------------------------------------- */
function html_compress($url) {
/*
+ Remove white spaces and tags before and after HTML tags
+ Remove comments
+ Replace multiple empty lines with just spaces and tabs with with a single empty line
+ Remove spaces and tabs that are between two HTML tags
+ Remove spaces, line breaks and tabs:
- After an end curly brace eventually followed by a comma
- Between and end brace and and start curly brace
- Between a comma and a curly brace
- Between a tag name and a tag value
*/
$regex = array(
'/\>[^\S ]+/s' => '>',
'/[^\S ]+\</s' => '<',
'/([\t ])+/s' => ' ',
'/^([\t ])+/m' => '',
'/([\t ])+$/m' => '',
'~//[a-zA-Z0-9 ]+$~m' => '',
'/[\r\n]+([\t ]?[\r\n]+)+/s' => "\n",
'/\>[\r\n\t ]+\</s' => '><',
'/}[\r\n\t ]+/s' => '}',
'/}[\r\n\t ]+,[\r\n\t ]+/s' => '},',
'/\)[\r\n\t ]?{[\r\n\t ]+/s' => '){',
'/,[\r\n\t ]?{[\r\n\t ]+/s' => ',{',
'/\),[\r\n\t ]+/s' => '),',
'~([\r\n\t ])?([a-zA-Z0-9]+)=\"([a-zA-Z0-9_\\-]+)\"([\r\n\t ])?~s' => '$1$2=$3$4');
return preg_replace(array_keys($regex), array_values($regex), file_get_contents($url));
}
$url = 'https://www.heise.de/';
echo '<base href="'.$url.'" />'.html_compress($url);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment