Created
June 7, 2014 12:06
-
-
Save taufik-nurrohman/db723da29e69065a1130 to your computer and use it in GitHub Desktop.
PHP CSS Minifier
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// http://ideone.com/Q5USEF | |
<?php | |
function minify_css($str){ | |
# remove comments first (simplifies the other regex) | |
$re1 = <<<'EOS' | |
(?sx) | |
# quotes | |
( | |
"(?:[^"\\]++|\\.)*+" | |
| '(?:[^'\\]++|\\.)*+' | |
) | |
| | |
# comments | |
/\* (?> .*? \*/ ) | |
EOS; | |
$re2 = <<<'EOS' | |
(?six) | |
# quotes | |
( | |
"(?:[^"\\]++|\\.)*+" | |
| '(?:[^'\\]++|\\.)*+' | |
) | |
| | |
# ; before } (and the spaces after it while we're here) | |
\s*+ ; \s*+ ( } ) \s*+ | |
| | |
# all spaces around meta chars/operators | |
\s*+ ( [*$~^|]?+= | [{};,>~+-] | !important\b ) \s*+ | |
| | |
# spaces right of ( [ : | |
( [[(:] ) \s++ | |
| | |
# spaces left of ) ] | |
\s++ ( [])] ) | |
| | |
# spaces left (and right) of : | |
\s++ ( : ) \s*+ | |
# but not in selectors: not followed by a { | |
(?! | |
(?> | |
[^{}"']++ | |
| "(?:[^"\\]++|\\.)*+" | |
| '(?:[^'\\]++|\\.)*+' | |
)*+ | |
{ | |
) | |
| | |
# spaces at beginning/end of string | |
^ \s++ | \s++ \z | |
| | |
# double spaces to single | |
(\s)\s+ | |
EOS; | |
$str = preg_replace("%$re1%", '$1', $str); | |
return preg_replace("%$re2%", '$1$2$3$4$5$6$7', $str); | |
} | |
$in = <<<'EOS' | |
p * i , html | |
/* remove spaces */ | |
/* " comments have no escapes \*/ | |
body/* keep */ /* space */p, | |
p [ remove ~= " spaces " ] :nth-child( 3 + 2n ) > b span i , div::after | |
{ | |
/* comment */ | |
background : url( " /* string */ " ) blue !important ; | |
content : " escapes \" allowed \\" ; | |
width: calc( 100% - 3em + 5px ) ; | |
margin-top : 0; | |
margin-bottom : 0; | |
margin-left : 10px; | |
margin-right : 10px; | |
} | |
EOS; | |
$out = minify_css($in); | |
echo "input:\n"; | |
var_dump($in); | |
echo "\n\n"; | |
echo "output:\n"; | |
var_dump($out); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment