2014-09-28 48 views
0

我試圖用其他圖像URL替換所有圖像網址,但我沒有成功地正確編寫正則表達式。PHP - 'preg_replace正則表達式'所有圖像'網址

我的圖像不一定在img標記與src=""

它主要與="image url"

內容封閉,以取代例如:

[side_section poster="image.jpg" position="left" bgrepeat="no-repeat" bgcolor="#f6f6f6" paddingtop="70" paddingbot="70" txtcolor="" ] 

$content = (string) preg_replace('/(?[!=")(http:\\/\\/.+(png|jpeg|jpg|gif|bmp))/Ui', './images/placeholder.png', (string) $content); 
+0

你能提供一些示例URL和SH我們期待什麼? – 2014-09-28 22:46:08

+0

當我看到'(?[!=「)'時,我很擔心。嘗試使用像regex101.com這樣的在線工具。我也有點擔心你製作的隨機類型劇集。 – HamZa 2014-09-28 22:48:34

+0

我知道我是我的形象永遠是這樣的:'[... =「image.jpg」...]' – freaky 2014-09-28 22:49:57

回答

2

這裏是你需要的東西:

$content = '[side_section poster="image.jpg" position="left" bgrepeat="no-repeat" bgcolor="#f6f6f6" paddingtop="70" paddingbot="70" txtcolor="" ]'; 
$newContent = (string) preg_replace('/="([^"]*\.(?:png|jpeg|jpg|gif|bmp))"/', '="./images/placeholder.png"', (string) $content); 
echo $newContent; 

使用的正則表達式是:="([^"]*\.(?:png|jpeg|jpg|gif|bmp))"

你可以在這裏測試它:DEMO

但是,你用它來替換你的圖像路徑字符串應該是這樣的:'="./images/placeholder.png"'

作爲替代使用此功能:

function replaceImg($content, $path) 
{ 
    return (string) preg_replace('/="([^"]*\.(?:png|jpeg|jpg|gif|bmp))"/', '="'.$path.'"', (string) $content); 
} 

例如

$content = '[side_section poster="image.jpg" position="left" bgrepeat="no-repeat" bgcolor="#f6f6f6" paddingtop="70" paddingbot="70" txtcolor="" ]'; 
echo replaceImg($content, './images/placeholder.png'); 

輸出

[side_section poster="./images/placeholder.png" position="left" bgrepeat="no-repeat" bgcolor="#f6f6f6" paddingtop="70" paddingbot="70" txtcolor="" ] 

例如2

$content = 'position="left" poster="image.jpg"'; 
echo replaceImg($content, './images/placeholder.png'); 

輸出

position="left" poster="./images/placeholder.png" 
+0

工程就像一個魅力!謝謝 – freaky 2014-09-28 23:01:17

+0

而不是使用'。*'使用'[^ 「] *'否則就像'position =」left「poster =」image.jpg「'會給你錯誤的結果。 – 2014-09-28 23:03:46

+0

@CasimiretHippolyte感謝您注意 – 2014-09-28 23:05:10