Parse CSS in PHP
I need to parse a CSS file and chang开发者_StackOverflowe 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
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 beurl(
(?=\))
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).
Use regular expressions and preg_replace
. Something like:
url\(([^\)]+)\)
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)}
Maybe you can try looking at: preg_replace()
精彩评论