2011-09-14 76 views
-2

我想替換下面的圖片源 http://www.fishingwithdon.com/wp-content/uploads/2006/06/drop_off_area.jpg需要正則表達式替換

http://www.test.com/test/uploads/2006/06/drop_off_area.jpg

意味着我要替換「http://www.fishingwithdon.com/wp圖像源的一部分-content /「與」http://www.test.com/test/「

但是我想要替換的字符串每次都不一樣。

任何幫助將不勝感激。

感謝,

Umesh製作庫卡尼

+0

如果該字符串不會是每次都一樣,你怎麼打算預測字符串將是什麼? – afuzzyllama

回答

1
preg_replace ('/^(http:).*(\/)$/', 'http://www.test.com/test/', $src) 

這應該做的伎倆

1
$str = preg_replace(
    '~\bhttp://www\.fishingwithdon\.com/wp-content/~', 
    'http://www.test.com/test/', 
    $str 
); 

http://codepad.org/xTvLGXC8

但不會簡單的str_replace你的情況是否足夠?

+0

http:// www \ .fishingwithdon \ .com/wp-content /每次都不一樣 –

0
$html = "<img src=\"http://www.fishingwithdon.com/wp-content/uploads/2006/06/drop_off_area.jpg\"/>"; 
preg_match_all('#<img[^>]*>#i', $html, $match); 
if(count($match) > 0) 
{ 
    foreach($match[0] as $image) 
    { 
     $new = preg_replace('/http:\/\/www\.(.+)\.com\//', 'http://www.test.com/test/', $image); 
     $html = str_replace($image, $new, $html); 
    } 
} 
echo $html; 

可以相應地修改調整爲不同的URL的情況下,即(非www,non-.com,HTTPS VS HTTP)

0

肯定你需要一個正則表達式嗎? str_replace是否足夠?它甚至說:

如果你不需要花哨的替換規則(如正則表達式),你應該總是使用這個函數,而不是preg_replace()。

例子:

$replace_needle = 'http://www.fishingwithdon.com/wp-content/'; 
$replacement = 'http://www.test.com/test/'; 
$replace_haystack = 'http://www.fishingwithdon.com/wp-content/uploads/2006/06/drop_off_area.jpg'; 
$result = str_replace($replace_needle, $replacement, $replace_haystack);