$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?
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
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);
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")
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.