Last active
November 23, 2021 10:19
-
-
Save enijar/6fae5be42d85fe436c32 to your computer and use it in GitHub Desktop.
Minify JavaScript and CSS Files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<style> | |
<?php | |
echo minifyCSS([ | |
'path/to/a.css', | |
'path/to/b.css' | |
]); | |
?> | |
</style> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Concatenate an array of files into a string | |
* | |
* @param $files | |
* @return string | |
*/ | |
function concatenateFiles($files) | |
{ | |
$buffer = ''; | |
foreach($files as $file) { | |
$buffer .= file_get_contents(__DIR__ . '/' . $file); | |
} | |
return $buffer; | |
} | |
/** | |
* @param $files | |
* @return mixed|string | |
*/ | |
function minifyCSS($files) | |
{ | |
$buffer = concatenateFiles($files); | |
$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer); | |
$buffer = str_replace(["\r\n","\r","\n","\t",' ',' ',' '], '', $buffer); | |
$buffer = preg_replace(['(( )+{)','({( )+)'], '{', $buffer); | |
$buffer = preg_replace(['(( )+})','(}( )+)','(;( )*})'], '}', $buffer); | |
$buffer = preg_replace(['(;( )+)','(( )+;)'], ';', $buffer); | |
return $buffer; | |
} | |
/** | |
* @param $files | |
* @return mixed|string | |
*/ | |
function minifyJS($files) { | |
$buffer = concatenateFiles($files); | |
$buffer = preg_replace("/((?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:\/\/.*))/", "", $buffer); | |
$buffer = str_replace(["\r\n","\r","\t","\n",' ',' ',' '], '', $buffer); | |
$buffer = preg_replace(['(( )+\))','(\)( )+)'], ')', $buffer); | |
return $buffer; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment