| 1 |
<?php |
| 2 |
|
| 3 |
namespace WPCoder\Optimization; |
| 4 |
|
| 5 |
class HTMLMinifier { |
| 6 |
|
| 7 |
public static function minify( $input ): string { |
| 8 |
if ( trim( $input ) === "" ) { |
| 9 |
return $input; |
| 10 |
} |
| 11 |
// Remove extra white-space(s) between HTML attribute(s) |
| 12 |
$input = preg_replace_callback( '#<([^\/\s<>!]+)(?:\s+([^<>]*?)\s*|\s*)(\/?)>#s', function ( $matches ) { |
| 13 |
return '<' . $matches[1] . preg_replace( '#([^\s=]+)(\=([\'"]?)(.*?)\3)?(\s+|$)#s', ' $1$2', $matches[2] ) . $matches[3] . '>'; |
| 14 |
}, str_replace( "\r", "", $input ) ); |
| 15 |
|
| 16 |
return preg_replace( |
| 17 |
array( |
| 18 |
// t = text |
| 19 |
// o = tag open |
| 20 |
// c = tag close |
| 21 |
// Keep important white-space(s) after self-closing HTML tag(s) |
| 22 |
'#<(img|input)(>| .*?>)#s', |
| 23 |
// Remove a line break and two or more white-space(s) between tag(s) |
| 24 |
'#(<!--.*?-->)|(>)(?:\n*|\s{2,})(<)|^\s*|\s*$#s', |
| 25 |
'#(<!--.*?-->)|(?<!\>)\s+(<\/.*?>)|(<[^\/]*?>)\s+(?!\<)#s', |
| 26 |
// t+c || o+t |
| 27 |
'#(<!--.*?-->)|(<[^\/]*?>)\s+(<[^\/]*?>)|(<\/.*?>)\s+(<\/.*?>)#s', |
| 28 |
// o+o || c+c |
| 29 |
'#(<!--.*?-->)|(<\/.*?>)\s+(\s)(?!\<)|(?<!\>)\s+(\s)(<[^\/]*?\/?>)|(<[^\/]*?\/?>)\s+(\s)(?!\<)#s', |
| 30 |
// c+t || t+o || o+t -- separated by long white-space(s) |
| 31 |
'#(<!--.*?-->)|(<[^\/]*?>)\s+(<\/.*?>)#s', |
| 32 |
// empty tag |
| 33 |
'#<(img|input)(>| .*?>)<\/\1>#s', |
| 34 |
// reset previous fix |
| 35 |
'#( ) (?![<\s])#', |
| 36 |
// clean up ... |
| 37 |
'#(?<=\>)( )(?=\<)#', |
| 38 |
// --ibid |
| 39 |
// Remove HTML comment(s) except IE and noindex comment(s) |
| 40 |
'#\s*<!--(?!(\[if\s)|(noindex)|(\/noindex)).*?-->\s*|(?<!\>)\n+(?=\<[^!])#s', |
| 41 |
//'#\s*<!--(?!\[if\s).*?-->\s*|(?<!\>)\n+(?=\<[^!])#s' - noindex fix |
| 42 |
), |
| 43 |
array( |
| 44 |
'<$1$2</$1>', |
| 45 |
'$1$2$3', |
| 46 |
'$1$2$3', |
| 47 |
'$1$2$3$4$5', |
| 48 |
'$1$2$3$4$5$6$7', |
| 49 |
'$1$2$3', |
| 50 |
'<$1$2', |
| 51 |
'$1 ', |
| 52 |
'$1', |
| 53 |
"" |
| 54 |
), |
| 55 |
$input ); |
| 56 |
} |
| 57 |
} |