![](/img/trans.png)
[英]PHP Regex to find and replace a string of 1 or more pipes with just 1 pipe
[英]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.