简体   繁体   English

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

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

I've got a css string like this : 我有这样的CSS字符串:

$string = "div#test {background: url(images/test.gif); width:100px; } div#test2 {background: url(../images/test2.gif); } ";

Basically I want to able to replace everything between url () to just the filename. 基本上,我希望能够将url()之间的所有内容替换为文件名。 So that it eventually looks like : 这样最终看起来像:

$string = "div#test {background: url(test.gif); width:100px; } div#test2 {background: url(test2.gif); } ";

Sort of like applying basename but for relative urls and for all such instances. 有点像应用基本名称,但适用于相对URL和所有此类实例。

Any ideas ? 有任何想法吗 ?

Try this: 尝试这个:

EDIT: I fixed the regex 编辑:我修复了正则表达式

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

taking for granted that u have the file name stored in a variable, you could use 认为您已经将文件名存储在变量中,您可以使用

$string = preg_replace('~url(.+)~', 'url(' . $filename . ')', $string);

www.regular-expressions.info is a good source if u want to learn regular expressions 如果您想学习正则表达式,www.regular-expressions.info是一个很好的来源

Assuming you don't have to match several div's in one string you could do something like this: 假设您不必在一个字符串中匹配多个div,则可以执行以下操作:

preg_replace(
    '@(.+url\()/?([^/]+/)*([^)]+)(\).+)@',
    '\\1\\3\\4',
    'div#test {background: url(images/test.gif); width:100px; }'
);

This also allows you to pass an array with multiple strings to replace 这也允许您传递带有多个字符串的数组来替换

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

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