[英]How can I make these relative URLs absolute using regular expressions?
I need to process CSS files to make any relative paths (using url()) absolute. 我需要处理CSS文件以使任何相对路径(使用url())都是绝对的。 It should match URIs in single or double quotes, or without quotes.
它应匹配单引号或双引号或不带引号的URI。 The replacement should not be quoted.
替代品不予报价。
Eg 例如
url(/foo/bar.png) --> url(/foo/bar.png) [unchanged]
url(foo/bar.png) --> url(/path/to/file/foo/bar.png) [made absolute]
url("foo/bar.png") --> url(/path/to/file/foo/bar.png) [made absolute, no quotes]
url('foo/bar.png') --> url(/path/to/file/foo/bar.png) [made absolute, no quotes]
I tried many different patterns, including a lookahead for / and many variations of the below. 我尝试了许多不同的模式,包括/的前瞻性以及以下内容的许多变体。
$dir = dirname($path);
$r = preg_replace('#url\(("|\')?([^/"\']{1}.+)("|\')?\)#', "url(/$dir/$2)", $contents);
Can't seem to get it right. 似乎无法正确解决。 Any help?
有什么帮助吗?
我想应该这样做:
$r = preg_replace('#url\(("|\'|)([^/"\'\)][^"\'\)]*)("|\'|)\)#', 'url(/'.$dir.'/$2)', $contents);
You could simplify two things. 您可以简化两件事。 First for matching quotes, you should use
["']?
rather than a group. And for detecting a relative path name, check for the presence of a letter rather than the absence of a slash. 首先,为了匹配引号,应使用
["']?
而不是组;并且要检测相对路径名,请检查是否存在字母而不是斜杠。
preg_replace('#url\( [\'"]? (\w[^)"\']+) [\'"]? \)#x'
I'm using )
to detect the end of the braces rather than .+
. 我正在使用
)
来检测括号的结尾,而不是.+
。 Though it would be more robust to list only allowed characters like [\\w/.]+
尽管只列出允许的字符(例如
[\\w/.]+
会更健壮
How about the following: 怎么样:
$pattern = '#url\([\'"]?(\w[\w\./]+)[\'"]?\)#i';
$subjects = array(
'url(/foo/bar.png)',
'url(foo/bar.png)',
'url("foo/bar.png")',
'url(\'foo/bar.png\')',
);
foreach ($subjects as $subject) {
echo "$subject => ", preg_replace($pattern, "url(/path/to/$1)", $subject), "\n";
}
Outputs the following: 输出以下内容:
url(/foo/bar.png) => url(/foo/bar.png)
url(foo/bar.png) => url(/path/to/foo/bar.png)
url("foo/bar.png") => url(/path/to/foo/bar.png)
url('foo/bar.png') => url(/path/to/foo/bar.png)
$dir = dirname($path);
$r = preg_replace('#url\(([\'"]?)([^/].*?)\1\)#', "url(/{$dir}/$2)", $contents);
url
url
Capturing group 2 contains the target data. 捕获组2包含目标数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.