I've got a css string like this :
$string = "div#test {background: url(images/test.gif); width:100px; } div#test2 {background: url(../images/test2.gif); } ";
Basically I want to able to replace everything between url () to just the filename. So that it eventually looks like :
$string = "div#test {background: url(test.gif); width:100px; } div#test2 {background: url(test2.gif); } ";
Sort of like applying basename but for relative urls and for all such instances.
Any ideas ?
Try this:
EDIT: I fixed the regex
<?php
$string = "div#test {background: url(images/test.gif); width:100px; } div#test2 {background: url(../images/test2.gif); } ";
$output = preg_replace('/([\.\w\/]*\/)/', '', $string);
var_dump($output);
string(93) "div#test {background: url(test.gif); width:100px; } div#test2 {background: url(test2.gif); } "
?>
taking for granted that u have the file name stored in a variable, you could use
$string = preg_replace('~url(.+)~', 'url(' . $filename . ')', $string);
www.regular-expressions.info is a good source if u want to learn regular expressions
Assuming you don't have to match several div's in one string you could do something like this:
preg_replace(
'@(.+url\()/?([^/]+/)*([^)]+)(\).+)@',
'\\1\\3\\4',
'div#test {background: url(images/test.gif); width:100px; }'
);
This also allows you to pass an array with multiple strings to replace
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.