tags:

views:

29

answers:

3
$contents = 'url("/test/what)';
echo preg_replace('/url\(([\'"]?)(?!(?:[a-z]+:)|\/|[\'"]\/)/i', 'url(\1'. '/prefix' . '\2', $contents);

I want to append /prefix to those urls that didn't use absolute path(start with /), the above works, but is pretty ugly.

Is there a more elegant solution?

A: 

if your problem is exactly what you posted (ie, getting a css background attribute set up correctly) then why not just:

if (substr($contents, 5, 1) != '/') 
    $contents = 'url("/prefix/' . substr($contents, 5);

EDIT: or if " there can be a whole bunch of stuff before url(" " then

$pos = strpos($contents, 'url("') + 5;
if (substr($contents, $pos, 1) != '/')
   $contents = substr($contents, 0, $pos) . '/prefix/' . substr($contents, $pos);
Scott Evernden
Because there can be a whole bunch of stuff before `url("` ... `$contents` is from a css file.
wamp
-1 This is broken
NullUserException
+1  A: 

Try this:

$regex = '~url\(([\'"]?)(?!/|[^:]+://)~';
echo preg_replace($regex, 'url($1' . '/prefix/', $contents);

It's very similar to your regex, but I don't think there is a lot of room for improvement if you want to use regex for this.

Demo: http://ideone.com/qeHna

Aillyn
No, this will also append prefix to absolute path like `url("/testuri"`
wamp
@wamp It's been fixed, demo updated as well
Aillyn
Please test with `$contents = 'url("/test/what)';` and your code will fail. And as I can predict,it's going to be the same as mine.
wamp
+1  A: 

Use negative look ahead :

$contents = 'url("/test/what")';
$prefix = '/prefix';
$regex = '~url\(([\'"]?)(?!>/|[^:]+://)~';
echo preg_replace($regex, 'url($1' . $prefix, $contents),"\n";

output :

url("/prefix/test/what")
M42