Minification is used to reduce the size of stylesheets or CSS by removing unnecessary unnecessary characters from code without changing the way that code works. There are a lot of PHP scripts to minify CSS in WordPress but we are going to use a simple function here. I use this function for inline CSS in my WordPress themes or plugins.
We will name the function minify_css()
with $css
parameter/argument which will be used to pass the css for minification. There is not much to explain in the following function as you can see what the preg_replace() and str_replace() functions are replacing step by step.
function minify_css($css) {
$css = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $css);
$css = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $css);
$css = str_replace(array('{ ', ' {'), '{', $css);
$css = str_replace(array('} ', ' }'), '}', $css);
$css = str_replace('; ', ';', $css);
$css = str_replace(': ', ':', $css);
$css = str_replace(', ', ',', $css);
$css = str_replace(array('> ', ' >'), '>', $css);
$css = str_replace(array('+ ', ' +'), '+', $css);
$css = str_replace(array('~ ', ' ~'), '~', $css);
$css = str_replace(';}', '}', $css);
return $css;
}
Muhammad Zohaib