PHP: Minify Code to Improve Performance

Here’s a quick and simple way to minify all your website’s code on-demand to improve website performance. Pass all of your website’s code into a function that strips out unnecessary stuff as follows:

[cc lang=”php”]/* remove all single line javascript comments */
/* replace all white spaces with a single space */
/* remove all multiline javascript and css comments */
/* remove all HTML comments */
$pattern = array(‘/s+//[[:print:]]+/’, ‘/s+/’, ‘//*.*?*//’, ‘/<!–.*?–>/’);
$replacement = array(”, ‘ ‘, ”, ”);
$minifiedcode = preg_replace($pattern, $replacement, $unminifiedcode);
[/cc]

WARNING: If your javascript is not well-coded (e.g. missing semi-colons), then you may get an error until you fix them.