简体   繁体   English

如何使用正则表达式使这些相对URL成为绝对的?

[英]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);
  • match url 匹配url
  • match open paren 比赛开放时间
  • open capture group 1 打开捕获组1
  • match ' or " zero or once 匹配“或”零或一次
  • close capturing group 1 关闭捕获组1
  • open capturing group 2 打开捕获组2
  • match one character that is not a / 匹配一个不是/的字符
  • match zero or more characters ungreedily 不满意地匹配零个或多个字符
  • close capturing group 2 关闭捕获组2
  • match whatever was captured in capturing group 1 (this ensures a same-quote match, and works if there is no quote captured by 1) 匹配捕获组1中捕获的任何内容(这确保了相同报价的匹配,并且如果没有被1捕获的引用也可以工作)
  • match a close paren 配对近亲

Capturing group 2 contains the target data. 捕获组2包含目标数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM