I am trying to construct a REGEX pattern, to convert relative URLs to absolute URLs in javascript scripts.
Example: I would like to replace ALL instances of the following (taken from js script):
url('fonts/fontawesome-webfont.eot?v=4.2.0');
And return the following:
url('http://example.com/fonts/fontawesome-webfont.eot?v=4.2.0');
Example pattern that works for HTML tags ( link ):
$pattern = "#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http)([^\"'>]+)([\"'>]+)#"
Preferred use of this pattern:
$result = preg_replace($pattern,'$1http://example.com/$2$3', $result);
The closest I have managed to guess (unsuccessfully) is:
$pattern = "#(url\s*=\s*[\"'])(?!http)([\"'])#";
Something like this might work for you:
/(?<=url\((['"]))(?!http)(?=.*?\1)/
With replacement:
http://example.com/
The above regex will match the position just after url('
where the quote can also be a double quote.
(?<=...) # is a positive lookbehind
(?!...) # is a negative lookahead
(?=...) # is a positive lookahead
\1 # refers to capturing group 1, in this case either ' or "
Note that lookbehinds isn't supported in JavaScript but are in PHP.
My testing shows that this will work: /url\\\\(['\\"](?!http[s]?:\\\\/\\\\/)(.+)['|\\"]\\\\)/
So your replace should look like:
preg_replace("/url\\\\(['\\"](?!http[s]?:\\\\/\\\\/)(.+)['|\\"]\\\\)/",'http://example.com/$1', $result)
Not a regex master tho - so take this with a grain of salt
我使用的解决方案(感谢来自andlrc和chris85的帮助):
$result = preg_replace("#(?<=url\((['\"]))(?!https?)#",'http://example.com/', $result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.