繁体   English   中英

正则表达式使用PHP将文件路径替换为字符串中的文件名

[英]regex to replace filepath to just filename in a string using php

我有这样的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#test2 {background: url(test2.gif); } ";

有点像应用基本名称,但适用于相对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; }'
);

这也允许您传递带有多个字符串的数组来替换

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM