使用regex缩小/压缩CSS? [英] Minify/compress CSS with regex?

查看:180
本文介绍了使用regex缩小/压缩CSS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中,您可以使用regex(PCRE)压缩/缩小CSS?



(在regex中理论上,这个井。)



背景注意:花费时间写一个删除(半废)问题,我想我会发布一个基本问题的一部分,并回答我的自我。希望可以。

解决方案

简单的regex CSS缩影器/压缩器



(Ok,可能不太简单,但很简单。)



需求



此回答假设要求是:




  • 删除评论

  • 替换长度超过1的空格组合 c

  • 删除元字符周围的所有空格: {} ; > + -

  • 删除周围的空格:重要

  • 删除周围的空格:
  • 删除 $ =
  • 之类的操作符周围的空格(除非在选择器中必须保留一个空格) >
  • 删除 / [ >) / ]

  • 删除字符串开头和结尾处的所有空格

  • 移除方块中的最后一个;

  • 不要更改字符串中的任何内容

  • 不必处理无效的CSS



请注意,这里的要求不包括将CSS属性转换为更短版本(如使用速记属性,而不是几个全长属性,删除不需要的引号)。
这是正则表达式一般不能解决的东西。



解决方案



更容易解决这个问题在两个通过:首先删除评论,然后一切。



应该可以在一个单一的通行证,但是你必须更换所有 \s ,其中一个表达式与空格和注释(以及其他一些修改)相匹配。



表达式删除评论:

 (?xs)
#quotes

?:[^\\] ++ | \\。)* +
|(?:[^'\\] ++ | '

|
#comments
/ \ *(?>。*?\ * /)
pre>

替换为 $ 1



删除您可以使用的所有其他内容:

 (?six)
#quotes
(?:[^'\\] ++ | \\。)* +
| * +'

|
#; before}(以及它之后的空格,我们在这里)
\s * +; \s * +(})\s * +
|
#元字符/运算符的所有空格
\s * +([* $〜^ |]?+ = | [{};,>〜+ - ] |!important )\s * +
|
#空格右边([:
([[(:])\s ++
|
左侧的空格]]
\s ++ )])
|
#左侧(右侧)的空格:
\s ++(:)\s * +
#但不在选择器中:后面不跟着{

(?>
[^ {}'] ++
|(?:[^\\] ++ | \\。)*
|'(?:[^'\\] ++ | \\。)* +'
)* +
{

|
字符串开头/结尾的空格
^ \s ++ | \s ++ \z
|
#双空格到单个
(\ s)\s +

替换为 $ 1 $ 2 $ 3 $ 4 $ 5 $ 6 $ 7



选择器检查在(负前瞻)可以减慢这种下降相比,正确的解析器。
Parsers已经知道他们是否在选择器中,并且不需要执行额外的搜索来检查。



PHP中的示例实现< h2>

 函数minify_css($ str){
#首先删除注释(简化另一个正则表达式)
$ re1 = <'EOS'
(?sx)
#quotes

(?:[^\\] ++ | \\\ \\。)* +
|'(?:[^'\\] ++ | \\。)* +'

|
| comments
/ \ *(?>。*?\ * /)
EOS;

$ re2 =<<<'EOS'
(?six)
#quotes

(?:[^\\] ++ | \\。)* +
| (?:[^'\\] ++ | \\。)* +'

|
#; before}(以及它之后的空格,我们在这里)
\s * +; \s * +(})\s * +
|
#元字符/运算符的所有空格
\s * +([* $〜^ |]?+ = | [{};,>〜+ - ] |!important )\s * +
|
#空格右边([:
([[(:])\s ++
|
左侧的空格]]
\s ++ )])
|
#左侧(右侧)的空格:
\s ++(:)\s * +
#但不在选择器中:后面不跟着{

(?>
[^ {}'] ++
|(?:[^\\] ++ | \\。)*
|'(?:[^'\\] ++ | \\。)* +'
)* +
{

|
字符串开头/结尾的空格
^ \s ++ | \s ++ \z
|
#双空格到单个
(\ s)\s +
EOS;

$ str = preg_replace(%$ re1%,'$ 1',$ str);
return preg_replace(%$ re2%,'$ 1 $ 2 $ 3 $ 4 $ 5 $ 6 $ 7',$ str);
}



快速测试



可在在ideone.com 找到:

  $ in =<<<'EOS'

p * i,html
/ *删除空格* /

/ *没有转义\ * /
body / * keep * / / * space * / p,
p [remove〜=spaces]:nth-​​child(3 + 2n)> b span i, div :: after

{
/ * comment * /
background:url(/ * string * /)blue!important;
content:escape \allowed \\;
width:calc(100% - 3em + 5px);
margin-top:0;
margin-bottom:0;
margin-left:10px;
margin-right:10px;
}

EOS;


$ out = minify_css($ in);

echoinput:\\\
;
var_dump($ in);

echo\\\
\\\
;
echooutput:\\\
;
var_dump($ out);

输出:

 code> input:
string(435)
p * i,html
/ *删除空格* /

/ * \\ * /
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; bottom:0;
margin-left:10px;
margin-right:10px;
}



输出:
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: left:10px; margin-right:10px}



比较



cssminifier.com



cssminifier.com 的结果对于与上述测试相同的输入:

  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} 

长度263字节。比上述正则表达式缩略词的输出长12个字节。



cssminifier.com 与这个正则表达式缩略器相比有一些缺点:




  • 它留下部分注释。

  • 它不会删除某些表达式中的运算符周围的空格

$(可能有一个原因。 b
$ b

CSSTidy



CSSTidy 1.3的输出(通过 codebeautifier.com )在最高压缩级别预设:

  /  /  /  /  p [remove〜=spaces]:nth-​​child(3 + 2n)> b span i,div :: after {background:url(/ * string * / \\allowed \\; width:calc(100%-3em + 5px); margin:0 10px;} 


b $ b

长度286字节。比正则表达式缩略器的输出长35个字节。



CSSTidy不会删除某些选择器中的注释或空格。但它确实缩小属性。



并列比较



针对与上述示例相同的输入的不同缩小器。
(用空格替换换行符)。

 这个回答(251):p * i,html body p ,p [remove〜=spaces]:nth-​​child(3 + 2n)> b span i,div :: after {background:url(/ * string * /)blue!important; content: \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) :: after {background:url(/ * string * /)blue!important; content:escapes \allowed \\; width:calc(100% - 3em + 5px); margin- 0; margin-bottom:0; margin-left:10px; margin-right:10px}
CSSTidy 1.3(286):p * i,html / * remove spaces * / / *注释没有转义\\ * / 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;}



对于普通CSS CSSTidy可能最好转换为速记属性。



我假设有其他minifiers(像YUI压缩程序)应该更好,并给出比这个正则表达式缩略词更短的结果。


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.

解决方案

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.

这篇关于使用regex缩小/压缩CSS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆