0

I need to parse a CSS file and change the path of an image in similar declarations to the following?

url("/images/...")

to basically change anything in between url("")


I want to replace

url('images/img.jpg'), url("images/img.jpg") 

and

url(images/img.jpg)

for url(/newpath/images/img.jpg)

I need to somehow get the current path so that I can append it to the new one

0

4 Answers 4

2

You can do this:

$line = "background-image: url(/images/image.png) no-repeat;";
//or $line = "background-image: url( /images/image.png ) no-repeat;";
echo preg_replace('/(?<=url\()[^\)]+(?=\))/x', '/newfolder/newimage.png', $line);

The regexp says:

  • [^\)]+ string of 1 caracter or more, without )
  • (?<=url\() before this string, there must be url(
  • (?=\)) after the string, there must be )
  • x whitespace data characters in the pattern are totally ignored except when escaped or inside a character class (more info).
Sign up to request clarification or add additional context in comments.

3 Comments

tip: use x modifier and put the explanation into the code. also you can use () for delimiters.
Added x modifier. I don't understand what u mean by () for delimiters. Feel free to edit my answer.
like this: codepad.org/cwV2Kphc. Makes it much easier to read this way IMO.
0

Use regular expressions and preg_replace. Something like:

url\(([^\)]+)\)

3 Comments

THanks for the replies, what i actually wnat is capture anythign inside url() and use it for my replacement string. Sorry for not being clear the first time.
The code above does exactly just that. You need to place url(\1) as a replacement in preg_match(). \1 contains the matched string inside the url()
preg_replace("/url(\"([^\"]+\"))", 'url("'.dirname($file).'/\1"), $cssContent); how can i take into account cases like url("") or url('') or url()
0

Or you could serve your css files as php scripts via .htaccess, like this:

<FilesMatch "\.css$">
    php_value default_mimetype "text/css"
    SetHandler application/x-httpd-php
</FilesMatch>

And then in every css file you could defined your media path and use it wherever you want, like:

<?php define('MEDIA_PATH', '../images/'); ?>
.class{background-image:url(<?php echo MEDIA_PATH;?>background.jpg)}

Comments

-1

Maybe you can try looking at: preg_replace()

1 Comment

at a guess, because you just provided a link... Nothing really useful as such

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.