I found the html minification code on the Internet. I would like to ask the knowledgeable, is there any sense from such a code? I am also interested in the possible load from using this code. I would also like to know which of the three options is better ?
In index.php which is at the root of the site above the line
@ob_start ();
insert code (option 1)
function sanitize_output($buffer) {
$search = array('/\>[^\S ] /s', '/[^\S ] \</s', '/(\s) /s', '/<!--(.*?)-->/', '/\>[^\S ] /s', '/[^\S ] \</s', '/(\s) /s');
$replace = array('>', '<', '\\1', '', '>', '<', '\\1');
$buffer = preg_replace($search, $replace, $buffer);
return $buffer;
}
OR option 2
function sanitize_output($buffer) {
$search = array('/\>[^\S ] /s', '/[^\S ] \</s', '/(\s) /s', '/<!--(.*?)-->/', '/\>[^\S ] /s', '/[^\S ] \</s', '/(\s) /s');
$replace = array('>', '<', '\\1', '<!--\\1-->', '>', '<', '\\1');
$buffer = preg_replace($search, $replace, $buffer);
return $buffer;
}
OR option 3
function sanitize_output($buffer) {
$search = array(
'/\>[^\S ] /s',
'/[^\S ] \</s',
'/\s{5,}/'
);
$replace = array(
'>',
'<',
'\\1'
);
$buffer = preg_replace($search, $replace, $buffer);
return $buffer;
}
Next in /engine/modules/main.php find
echo $tpl->result['main'];
replace with
ob_start("sanitize_output");
echo $tpl->result['main'];
ob_end_flush();
CodePudding user response:
It's not recommended to code compression methods by yourself, use the inbuilt compression instead. Here are some you may want:
- Gzip string compression: https://www.php.net/manual/en/function.gzcompress.php
- Output buffering with gzip handler: https://www.php.net/manual/en/function.ob-gzhandler.php
Furthermore, in your provided codes:
- Option 1 is basically deleting line breaks and comments in your code.
- Option 2 deletes line breaks only.
- Option 3 deletes line breaks only.
Option 1 deletes most things so it will be mostly minimized.
For options 1 and 2 I don't see any point in adding '/\>[^\S ] /s', '/[^\S ] \</s', '/(\s) /s'
, they are just doubling things.
It's not necessary to minimize html code, it reduces its readability (or maybe that's your purpose) and does not actually decrease the loading speed on small files (you need some MBs to see significant results) but may even increase it because it needs to perform regex checks.
See this wiki page for more info.