Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
    
Can you elaborate on what exactly you are doing? Are you trying to replace all the paths in a single CSS file? Multiple CSS files? Are there multiple paths that need to be replaced? If it is just for one file doing a simple find and replace in a text editor may prove to be the fastest solution. –  Jrod Jun 14 '12 at 19:23
    
Basically I have a wordpress plugin which loads all loaded css files. It combines them and writes them to a file in a different location. However, relative resource need to be converted to absolute ones in order for them to be loaded –  Friso Kluitenberg Jun 14 '12 at 19:27

1 Answer 1

up vote 2 down vote accepted

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);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.