Skip to content

Instantly share code, notes, and snippets.

@ericjames
Created May 27, 2017 06:08
Show Gist options
  • Save ericjames/46671e5539279c6523ef73e26874f568 to your computer and use it in GitHub Desktop.
Save ericjames/46671e5539279c6523ef73e26874f568 to your computer and use it in GitHub Desktop.
Concatenate or minify CSS and JS using php
<?php
/**
* @return none
*/
function prepareView()
{
compressFiles([
'css/src/normalize.css',
'css/src/styles.css',
], 'css/main.css');
compressFiles([
'js/src/jquery-1.8.1.min.js',
'js/src/map-assets.js',
'js/src/map-init.js',
'js/src/map-functions.js',
'js/src/map-route-lines.js',
'js/src/map-library.js',
'js/src/ui-functions.js',
], 'js/main.js');
}
/** Compress CSS */
function compressFiles($filePaths, $writeToPath)
{
$string = '';
foreach ($filePaths as $file) {
$string .= file_get_contents($file);
}
if (STATUS == 'production') {
$string = minify($string);
} else {
$string = concatenate($string);
}
file_put_contents($writeToPath, $string);
};
/**
* @param string $string Text
* @return mixed
*/
function minify($string)
{
//http://stackoverflow.com/questions/19509863/how-to-remove-js-comments-using-php
$pattern = '/(?:(?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:(?<!\:|\\\|\'|\")\/\/.*))/';
/* remove comments */
$string = preg_replace($pattern, '', $string);
/* remove tabs, spaces, new lines */
$string = preg_replace('/\t+|\0+|\n+|\r+/', '', $string);
/* remove blank spaces */
$string = str_replace([' ', ' ', ' '], '', $string);
return $string;
}
/**
* @param string $string Text
* @return mixed
*/
function concatenate($string)
{
//http://stackoverflow.com/questions/19509863/how-to-remove-js-comments-using-php
$pattern = '/(?:(?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:(?<!\:|\\\|\'|\")\/\/.*))/';
return $string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment