[英]How to write such a regex in PHP?
$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. 我想将/prefix
附加到那些不使用绝对路径的网址(以/
开头),上面的方法有效,但是非常难看。
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 演示: 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: 如果您的问题恰好是您发布的内容(即正确设置css background属性),那么为什么不这样做:
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 编辑:或如果“ url(”“之前可以有一堆东西
$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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.