Minify/compress CSS with regex?

前端 未结 4 1600
情深已故
情深已故 2020-12-13 14:26

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

4条回答
  •  庸人自扰
    2020-12-13 15:22

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

提交回复
热议问题