我正在将一些CSS文件合并,并将它们写入一个单独的目录中的文件。我试图替换相对url()
值,使其适用于新的文件位置,忽略任何绝对URL。以下是一些示例CSS:
#TEST {
background:url(test.jpg);
background:url( 'test.jpg' );
background:url("test.jpg" );
background:url(http://example.com/test.jpg);
background:url('https://example.com/test.jpg');
background:url("http://example.com/test.jpg");
background:url( '//example.com/test.jpg' );
background:url( "//example.com/test.jpg" );
background:url(//example.com/test.jpg);
}
任何不以 http://
、https://
或 //
开头的内容都应该在其前面注入 $path
(只匹配前三个)。
期望输出:
#TEST {
background:url(/themes/default/css/test.jpg);
background:url( '/themes/default/css/test.jpg' );
background:url("/themes/default/css/test.jpg" );
background:url(http://example.com/test.jpg);
background:url('https://example.com/test.jpg');
background:url("http://example.com/test.jpg");
background:url( '//example.com/test.jpg' );
background:url( "//example.com/test.jpg" );
background:url(//example.com/test.jpg);
}
然而,这段代码却相反地匹配了结果:
$path = '/themes/default/css/';
$search = '#url\(\s*([\'"]?)((http(s)?:)?//)#';
$replace = "url($1{$path}$2";
$css = preg_replace($search, $replace, $css);
我知道你可以使用类似于
!^(http)
的内容来不匹配以http
开头的字符串,但是我尝试过的所有方法都失败了(我很菜,不擅长正则表达式)。我一直在使用在线正则表达式测试工具来解决这个问题,但是我真的卡住了。这可能不是我用来解决编译CSS中路径问题的方法,但是有人能帮我解决这个正则表达式问题吗?或者有更好的解决方案吗?
\s*(['"])?
以捕获引号(如果有的话),以便将$path
放在引号内。 - mathematical.coffee?!
中的?
是什么意思,或者第一个?:
在(?:https?:)
中是用来干什么的。 - Wesley Murch(?:正则表达式)
就像(正则表达式)
一样,只是括号不会被保存。它被称为非捕获括号。如果我使用(https?)
,那么$1
中将包含http
或https
,而$2
中将包含引号。通过使用(?:https?)
,括号中的任何内容都不会被保存,而$1
中将包含引号。 - mathematical.coffee