$css = preg_replace(array('/\s*(\w)\s*{\s*/','/\s*(\S*:)(\s*)([^;]*)(\s|\n)*;(\n|\s)*/','/\n/','/\s*}\s*/'),
array('$1{ ','$1$3;',"",'} '), $css);
This snippet collapses every line. It leaves spaces within the property definition of the CSS code. This will minify CSS but not the comments.
Let me give an example; if you want to load existing file and minify it you can do it by readfile function:
$css = readfile("filename.css");
$css = preg_replace(array('/\s*(\w)\s*{\s*/','/\s*(\S*:)(\s*)([^;]*)(\s|\n)*;(\n|\s)*/','/\n/','/\s*}\s*/'),
array('$1{ ','$1$3;',"",'} '), $css);
If you need a function which will save minified css you can use this;
function minify(string $file)
{
$css = readfile($file); // reading file and its contents
$css = preg_replace(array('/\s*(\w)\s*{\s*/', '/\s*(\S*:)(\s*)([^;]*)(\s|\n)*;(\n|\s)*/', '/\n/', '/\s*}\s*/'),
array('$1{ ', '$1$3;', "", '} '), $css); // Collapsing every line
file_put_contents($file, $css); // Saving the minified css to file
}
So if you want multiple css files and minify every file at once here's the snippet;
function minify(array $files)
{
// if we want to minify multiple css files and return it once we can use arrays!
$return = array();
foreach ($files as $file) {
$css = readfile($file); // reading file and its contents
$css = preg_replace(array('/\s*(\w)\s*{\s*/', '/\s*(\S*:)(\s*)([^;]*)(\s|\n)*;(\n|\s)*/', '/\n/', '/\s*}\s*/'),
array('$1{ ', '$1$3;', "", '} '), $css); // Collapsing every line
array_push($return, $css);
}
// Returning all css in once!
return implode("\n", $return);
}
To Save every minified css in one file;
function minify(array $files, string $output = "all.min.css")
{
// if we want to minify multiple css files and return it once we can use arrays!
$return = array();
foreach ($files as $file) {
$css = readfile($file); // reading file and its contents
$css = preg_replace(array('/\s*(\w)\s*{\s*/', '/\s*(\S*:)(\s*)([^;]*)(\s|\n)*;(\n|\s)*/', '/\n/', '/\s*}\s*/'),
array('$1{ ', '$1$3;', "", '} '), $css); // Collapsing every line
array_push($return, $css);
}
// Returning all css in once!
$implode = implode("\n", $return);
// Putting all minidied css into output file
file_put_contents($output, $implode);
}
*is a special char in regex so needs to be escaped. Short snippet of$minifywould help question... might be looking for/\*[^*]*\*+([^/][^*]\**+)*ob_startcalls it and takes the full page generation as the parameter. Soreset.css,application.css, andresponsive.cssare stitched together then replacements are run on them