Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_match: javascript url string

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)([\"'])#";
like image 801
leenremm Avatar asked Mar 07 '26 15:03

leenremm


1 Answers

Something like this might work for you:

/(?<=url\((['"]))(?!http)(?=.*?\1)/

With replacement:

http://example.com/

Regex Demo

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.

like image 163
Andreas Louv Avatar answered Mar 09 '26 05:03

Andreas Louv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!