Search code examples
cssregexstylesheet

Regular Expression - replace urls in style tags


I have searched on google and stackoverflow but didnt find a good answer. I also tryed it by myself, but iam no regex guru.

My goal is to replace all relative urls in a html style tag with the absolute version.

e.g.

  • style="url(/test.png)" with style="url(http://mysite.com/test.png)"
  • style="url("/test.png")" with style="url("http://mysite.com/test.png")"
  • style="url('/test.png')" with style="url('http://mysite.com/test.png')"
  • style="url(../test.png)" with style="url(http://mysite.com/test.png)"
  • style="url("../test.png")" with style="url('http://mysite.com/test.png')"
  • style="url('../test.png')" with style="url('http://mysite.com/test.png')"

and so on.

Here what i tryed with my poor regex "skils"

url\((?<Url>[^\)]*)\)

gives me the url in the "url" function.

thanks in advance!


Solution

  • Well, you can try the regex:

    style="url\((['"])?(?:\.\.)?(?<url>[^'"]+)\1?\)"
    

    And replace with:

    style="url($1http://mysite.com$2$1)"
    

    regex101 demo

    (['"])? will capture quotes if they are present and use them again at \1?

    ([^'"]+) will capture the url itself.