Skip to content

Instantly share code, notes, and snippets.

@enijar
Last active November 23, 2021 10:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save enijar/6fae5be42d85fe436c32 to your computer and use it in GitHub Desktop.
Save enijar/6fae5be42d85fe436c32 to your computer and use it in GitHub Desktop.
Minify JavaScript and CSS Files
<style>
<?php
echo minifyCSS([
'path/to/a.css',
'path/to/b.css'
]);
?>
</style>
<?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