I need to process CSS files to make any relative paths (using url()) absolute. It should match URIs in single or double quotes, or without quotes. The replacement should not be quoted.
E.g.
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?
I guess this should do it: