regex使用php将filepath替换为字符串中的文件名
我有一个css字符串,如下所示:regex使用php将filepath替换为字符串中的文件名,php,regex,dom,Php,Regex,Dom,我有一个css字符串,如下所示: $string = "div#test {background: url(images/test.gif); width:100px; } div#test2 {background: url(../images/test2.gif); } "; 基本上,我希望能够替换url到文件名之间的所有内容。因此,它最终看起来像: $string = "div#test {background: url(test.gif); width:100px; } div#tes
$string = "div#test {background: url(images/test.gif); width:100px; } div#test2 {background: url(../images/test2.gif); } ";
基本上,我希望能够替换url到文件名之间的所有内容。因此,它最终看起来像:
$string = "div#test {background: url(test.gif); width:100px; } div#test2 {background: url(test2.gif); } ";
有点像应用basename,但适用于相对URL和所有此类实例
有什么想法吗?试试这个:
编辑:我修正了正则表达式
<?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); } "
?>
假定文件名存储在变量中,您可以使用
$string = preg_replace('~url(.+)~', 'url(' . $filename . ')', $string);
www.regular-expressions.info是一个很好的来源,如果你想学习正则表达式,假设你不必在一个字符串中匹配多个div,你可以这样做:
preg_replace(
'@(.+url\()/?([^/]+/)*([^)]+)(\).+)@',
'\\1\\3\\4',
'div#test {background: url(images/test.gif); width:100px; }'
);
这还允许您传递带有多个字符串的数组以替换这与什么有关?你调查过什么了吗对于正则表达式构造,有一些工具,请参阅,不,我没有存储文件名。使用jack的解决方案。或者,您可能需要先编写3-4行代码才能获得文件名。因此,我还想过滤掉任何绝对URL组件http/https/ftp,我可以使用ht | ftps |执行OR操作吗\/\/