user263078
user263078

Reputation:

Replace CSS url()'s?

Imagine I have a string, $my_css_string, and we know it contains CSS styling.

Now imagine I have a function string url_replace(string $url) that returns a modified URL that I want to replace every url() with in $my_css_string.

So, for simplicity's sake, let's say url_replace() ALWAYS returns the string "xxxx".

How can you go through $my_css_string, find each url() in the string, and replace that URL with what you get from url_replace()?


So, if you had this CSS as $my_css_string:

@import url('http://example.com/css/animals.css');
.dog {
    background:url("/images/dog.png");
    border:1px solid rgb(0,0,128);
}
.cat {
    background:url(http://example.com/images/cat.gif);
}

If you ran the code, $my_css_string would become:

@import url('xxxx');
.dog {
    background:url( "xxxx" );
    border:1px solid rgb(0,0,128);
}
.cat {
    background:url(xxxx);
}

Notice how it needs to handle multiple ways of defining URLs.

How do I do that?

Upvotes: 1

Views: 1357

Answers (3)

Qtax
Qtax

Reputation: 33908

If you are not that picky you could use the following expression to match url()s:

/\b url\( \s*+ \K  (?| (") ( (?>[^"\\]++|\\.)*+ ) " | (') ( (?>[^'\\]++|\\.)*+ ) ' | () ([\S)]*+) )  ( \s*+ \) )/ix

This expression will handle escapes correctly, but could also match in comments and strings, which may not be desired.

And then you can use it with preg_replace_callback or just with /e, eg:

preg_replace('/\b url\( \s*+ \K  (?| (") ( (?>[^"\\\\]++|\\\\.)*+ ) " | (\') ( (?>[^\'\\\\]++|\\\\.)*+ ) \' | () ([\S)]*+) )  ( \s*+ \) )/ixe', '"$1" . url_replace("$2") . "$1$3"', $css);

Upvotes: 0

hohner
hohner

Reputation: 11578

You want to use preg_replace_callback:

$my_new_css_string = preg_replace_callback(
                        '/background-image:\s*url\(\s*([\'"]*)(?P<file>[^\1]+)\1\s*\)/i',
                        'url_replace',
                        $my_css_string);

Upvotes: 2

vansimke
vansimke

Reputation: 974

Have you looked at this: https://www.php.net/manual/en/function.preg-replace-callback.php. You should be able to search for 'url(.*)' and then implement custom logic in the call back to handle the various replacement scenarios.

Upvotes: 0

Related Questions