我有一个困难的正则表达式问题。我有这个表达式来检测绝对 url(http 和 https
/(url {0,}\(( {0,}'| {0,}"|))(?!http|data\:).*?\)/im
我基本上想做的是使用 preg_replace
在 url 前加上我的脚本中定义的路径 $path
。基本上这个正则表达式会产生两个捕获组:
group 1: (url {0,}\(( {0,}'| {0,}"|))(?!http).*?\)
group 2: ( {0,}'| {0,}"|)
我如何才能一直匹配到 uri 开始,然后在它前面加上 $path
?我似乎无法正确设置捕获组。
最佳答案
你可以这样使用:
$re = '/\b url \s*+ \( \s*+ (?| " ([^"]*+) " | \' ([^\']*+) \' | (\S*+) ) \s*+ \) /ix';
$str = preg_replace_callback($re, function ($match) {
$url = $match[1];
// do some check on the url
if(whatever)
return $match[0]; // return without change
// do whatever you want with the URL
// return new url
return "url(\"$url\")";
}, $str);
关于PHP 正则表达式 : CSS Relative to Absolute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11039758/