Skip to content

Instantly share code, notes, and snippets.

@geminorum
Created August 28, 2014 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geminorum/8e0c834a9a23834dbadc to your computer and use it in GitHub Desktop.
Save geminorum/8e0c834a9a23834dbadc to your computer and use it in GitHub Desktop.
A set of regular expressions in PHP to minify a string of CSS. https://github.com/GaryJones/Simple-PHP-CSS-Minification/
<?php
/**
* Quick and dirty way to mostly minify CSS.
*
* @since 1.0.0
* @author Gary Jones
*
* @param string $css CSS to minify
* @return string Minified CSS
*/
function minify( $css ) {
// Normalize whitespace
$css = preg_replace( '/\s+/', ' ', $css );
// Remove spaces before and after comment
$css = preg_replace( '/(\s+)(\/\*(.*?)\*\/)(\s+)/', '$2', $css );
// Remove comment blocks, everything between /* and */, unless
// preserved with /*! ... */ or /** ... */
$css = preg_replace( '~/\*(?![\!|\*])(.*?)\*/~', '', $css );
// Remove ; before }
$css = preg_replace( '/;(?=\s*})/', '', $css );
// Remove space after , : ; { } */ >
$css = preg_replace( '/(,|:|;|\{|}|\*\/|>) /', '$1', $css );
// Remove space before , ; { } ( ) >
$css = preg_replace( '/ (,|;|\{|}|\(|\)|>)/', '$1', $css );
// Strips leading 0 on decimal values (converts 0.5px into .5px)
$css = preg_replace( '/(:| )0\.([0-9]+)(%|em|ex|px|in|cm|mm|pt|pc)/i', '${1}.${2}${3}', $css );
// Strips units if value is 0 (converts 0px to 0)
$css = preg_replace( '/(:| )(\.?)0(%|em|ex|px|in|cm|mm|pt|pc)/i', '${1}0', $css );
// Converts all zeros value into short-hand
$css = preg_replace( '/0 0 0 0/', '0', $css );
// Shortern 6-character hex color codes to 3-character where possible
$css = preg_replace( '/#([a-f0-9])\\1([a-f0-9])\\2([a-f0-9])\\3/i', '#\1\2\3', $css );
return trim( $css );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment