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 ?

mario
  • 144,265
  • 20
  • 237
  • 291
Ashesh
  • 939
  • 2
  • 11
  • 28
  • What does this have to do with [dom](http://stackoverflow.com/questions/tagged/dom)? And did you investigate anything yet? -- For regex construction there are some tools, see [Open source RegexBuddy alternatives](http://stackoverflow.com/questions/89718/is-there) and [Online regex testing](http://stackoverflow.com/questions/32282/regex-testing) – mario May 18 '12 at 15:12

3 Answers3

0

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); } "
?>
Yago Riveiro
  • 727
  • 13
  • 28
0

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

Leandro Zhuzhi
  • 304
  • 1
  • 7
  • 17
0

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

baloo
  • 7,635
  • 4
  • 27
  • 35
  • And lets so I also wanted to filter out any absolute URL components (http/https/ftp), could I do an OR operation with (ht|f)tp(s|):\/\/) – Ashesh May 18 '12 at 15:42