28

In PHP can you compress/minify CSS with regex (PCRE)?

(As a theoretical in regex. I'm sure there are libraries out there that do this well.)

Background note: After spending hours writing an answer to a deleted (half crap) question, I thought I'd post a part of the underlying question and answer it my self. Hope it's ok.

4

4 に答える 4

49

Simple regex CSS minifier/compressor

(Ok, it may not be overly simple, but pretty straight forward.)

Requirements

This answer assumes that the requirements are:

  • Remove comments
  • Replace whitespace combinations longer than 1 space with a single space
  • Remove all whitespace around the meta characters: {, }, ;, ,, >, ~, +, -
  • Remove spaces around !important
  • Remove spaces around :, except in selectors (where you have to keep a space before it)
  • Remove spaces around operators like $=
  • Remove all spaces right of (/[ and left of )/]
  • Remove all spaces at the beginning and end of string
  • Remove the last ; in a block
  • Don't change anything in strings
  • Doesn't have to work on invalid CSS

Note that the requirements here do not include converting CSS properties to shorter versions (like using shorthand properties instead of several full length properties, removing quotes where not required). This is something that regex would not be able to solve in general.

Solution

It's easier to solve this in two passes: first remove the comments, then everything else.

It should be possible to do in a single pass, but then you have to replace all \s with an expression that matches both spaces and comments (among some other modifications).

The first pass expression to remove comments:

(?xs)
  # quotes
  (
    "(?:[^"\\]++|\\.)*+"
  | '(?:[^'\\]++|\\.)*+'
  )
|
  # comments
  /\* (?> .*? \*/ )

Replace with $1.

And to remove everything else you can use:

(?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+

Replaced with $1$2$3$4$5$6$7.

The selector check for removing spaces before : (the negative lookahead) can slow this down compared to proper parsers. Parsers already know if they are in a selector or not, and don't have to do extra searches to check that.

Example implementation in 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);
}

Quick test

Can be found at ideone.com:

$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);

Output:

input:
string(435) "
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;
}
"


output:
string(251) "p * i,html body p,p [remove~=" spaces  "] :nth-child(3+2n)>b span i,div::after{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}"

Compared

cssminifier.com

Results of cssminifier.com for the same input as the test above:

p * i,html /*\*/body/**/p,p [remove ~= " spaces  "] :nth-child(3+2n)>b span i,div::after{background:url("  /* string */  ") blue;content:" escapes \" allowed \\";width:calc(100% - 3em+5px);margin-top:0;margin-bottom:0;margin-left:10px;margin-right:10px}

Length 263 byte. 12 byte longer than the output of the regex minifier above.

cssminifier.com has some disadvantages compared to this regex minifier:

  • It leaves parts of comments. (There may be a reason for this. Maybe some CSS hacks.)
  • It doesn't remove spaces around operators in some expressions

CSSTidy

Output of CSSTidy 1.3 (via codebeautifier.com) at highest compression level preset:

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{background:url("  /* string */  ") blue!important;content:" escapes \" allowed \\";width:calc(100%-3em+5px);margin:0 10px;}

Length 286 byte. 35 byte longer than the output of the regex minifier.

CSSTidy doesn't remove comments or spaces in some selectors. But it does minify to shorthand properties. The latter should probably help compress normal CSS a lot more.

Side by side comparison

Minified output from the different minifiers for the same input as in the above example. (Leftover line breaks replaced with spaces.)

this answern    (251): p * i,html body p,p [remove~=" spaces  "] :nth-child(3+2n)>b span i,div::after{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}
cssminifier.com (263): p * i,html /*\*/body/**/p,p [remove ~= " spaces  "] :nth-child(3+2n)>b span i,div::after{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}
CSSTidy 1.3     (286): 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{background:url("  /* string */  ") blue!important;content:" escapes \" allowed \\";width:calc(100%-3em+5px);margin:0 10px;}

For normal CSS CSSTidy is probably best as it converts to shorthand properties.

I assume there are other minifiers (like the YUI compressor) that should be better at this, and give shorter result than this regex minifier.

于 2013-03-04T06:24:22.660 に答える
6

Here's a slightly modified version of @Qtax's answer which resolves the issues with calc() thanks to an alternative regex from @matthiasmullie's Minify library.

function minify_css( $string = '' ) {
    $comments = <<<'EOS'
(?sx)
    # don't change anything inside of quotes
    ( "(?:[^"\\]++|\\.)*+" | '(?:[^'\\]++|\\.)*+' )
|
    # comments
    /\* (?> .*? \*/ )
EOS;

    $everything_else = <<<'EOS'
(?six)
    # don't change anything inside of quotes
    ( "(?:[^"\\]++|\\.)*+" | '(?:[^'\\]++|\\.)*+' )
|
    # spaces before and after ; and }
    \s*+ ; \s*+ ( } ) \s*+
|
    # all spaces around meta chars/operators (excluding + and -)
    \s*+ ( [*$~^|]?+= | [{};,>~] | !important\b ) \s*+
|
    # all spaces around + and - (in selectors only!)
    \s*([+-])\s*(?=[^}]*{)
|
    # spaces right of ( [ :
    ( [[(:] ) \s++
|
    # spaces left of ) ]
    \s++ ( [])] )
|
    # spaces left (and right) of : (but not in selectors)!
    \s+(:)(?![^\}]*\{)
|
    # spaces at beginning/end of string
    ^ \s++ | \s++ \z
|
    # double spaces to single
    (\s)\s+
EOS;

    $search_patterns  = array( "%{$comments}%", "%{$everything_else}%" );
    $replace_patterns = array( '$1', '$1$2$3$4$5$6$7$8' );

    return preg_replace( $search_patterns, $replace_patterns, $string );
}
于 2017-06-04T02:16:15.200 に答える
0

This question is specifically about PHP, but since this post was at the top of the results when I Googled "minify css regex", I'm posting a Python adaptation here:

#!/usr/bin/env python
# These regexes were adapted from PCRE patterns by Dustin "lots0logs" Falgout,
# Matthias Mullie (https://stackoverflow.com/a/15195752/299196), and Andreas
# "Qtax" Zetterlund (https://stackoverflow.com/a/44350195/299196).
import re

CSS_COMMENT_STRIPPING_REGEX = re.compile(r"""
    # Quoted strings
    ( "(?:[^"\\]+|\\.)*" | '(?:[^'\\]+|\\.)*' )
    |
    # Comments
    /\* ( .*? \*/ )
    """,
    re.DOTALL | re.VERBOSE
)

CSS_MINIFICATION_REGEX = re.compile(r"""
    # Quoted strings
    ( "(?:[^"\\]+|\\.)*" | '(?:[^'\\]+|\\.)*' )
    |
    # Spaces before and after ";" and "}"
    \s* ; \s* ( } ) \s*
    |
    # Spaces around meta characters and operators excluding "+" and "-"
    \s* ( [*$~^|]?= | [{};,>~] | !important\b ) \s*
    |
    # Spaces around "+" and "-" in selectors only
    \s*([+-])\s*(?=[^}]*{)
    |
    # Spaces to the right of "(", "[" and ":"
    ( [[(:] ) \s+
    |
    # Spaces to the left of ")" and "]"
    \s+ ( [])] )
    |
    # Spaces around ":" outside of selectors
    \s+(:)(?![^\}]*\{)
    |
    # Spaces at the beginning and end of the string
    ^ \s+ | \s+ \z
    |
    # Collapse concurrent spaces
    (\s)\s+
    """,
    re.DOTALL | re.IGNORECASE | re.VERBOSE
)

def minify_css(css):
    return CSS_MINIFICATION_REGEX.sub(r"\1\2\3\4\5\6\7\8",
        CSS_COMMENT_STRIPPING_REGEX.sub(r"\1", css))

The may not be the exact same as the PHP+PCRE versions. Since Python's regular expression library doesn't support many of the constructs that PCRE does, I had to modify PCRE patterns. The modifiers I removed improve performance and potentially harden the regex against malicious input, so it's probably not a good idea to use this on untrusted input.

于 2018-06-07T07:45:11.090 に答える
-1

Here is a compact source of how I do it. With compression. And you don't have to care, if you changed something in the source.

In fact '//comments' are not allowed in css.

ob_start('ob_handler');
if(!file_exists('style/style-min.css) 
or filemtime('style/style.css') > filemtime('style/style-min.css')){
  $css=file_get_contents('style/style.css');    
  //you need to escape some more charactes if pattern is an external string.
  $from=array('@\\s*/\\*.*\\*/\\s*@sU', '/\\s{2,}/');
  $to=  array(''                      , ' ');
  $css=preg_replace($from,$to,$css); 
  $css=preg_replace('@\s*([\:;,."\'{}()])\s*@',"$1",$css);  
  $css=preg_replace('@;}@','}',$css);
  header('Content-type: text/css');
  echo $css;
  file_put_contents('style/style-min.css',$css);
  //etag- modified- cache-control- header
  }
else{
  //exit if not modified?
  //etag- modified- cache-control- header
  header('Content-type: text/css');
  readfile('style/style-min.css');
  }   
ob_end_flush();

PS Who gave me the minus before I'm ready with typing? QTax- For a short time I forgot to escape the backslashes in the $fom array. PSS. Only new version of PHP undestand the 'U' param which makes a regex ungreedy.

于 2013-11-03T11:47:16.327 に答える