0

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 ?

4

3 回答 3

0

尝试这个:

编辑:我修复了正则表达式

<?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); } "
?>
于 2012-05-18T15:12:22.720 回答
0

理所当然地认为您将文件名存储在变量中,您可以使用

$string = preg_replace('~url(.+)~', 'url(' . $filename . ')', $string);

如果您想学习正则表达式,www.regular-expressions.info 是一个很好的来源

于 2012-05-18T15:16:57.690 回答
0

假设您不必在一个字符串中匹配多个 div,您可以执行以下操作:

preg_replace(
    '@(.+url\()/?([^/]+/)*([^)]+)(\).+)@',
    '\\1\\3\\4',
    'div#test {background: url(images/test.gif); width:100px; }'
);

这也允许您传递一个包含多个字符串的数组来替换

于 2012-05-18T15:24:59.573 回答