Search code examples
phpcssregexurlrelative-path

PHP Regex: CSS Relative to Absolute


I have a problem with a difficult regex. I have this expression to detect absolute urls (http and https

/(url {0,}\(( {0,}'| {0,}"|))(?!http|data\:).*?\)/im

What I want to do basically is with preg_replace to prepend the url with a path $path defined in my script. Basically this regex results in two capture groups:

group 1: (url {0,}\(( {0,}'| {0,}"|))(?!http).*?\)

group 2: ( {0,}'| {0,}"|)

How can I match all the way until the uri starts and then prepend it with $path? I can't seem to get the capturing groups right.


Solution

  • You can use something like this:

    $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);