2014-02-19 87 views
0

我正試圖實現這一點。我有很多看起來像這樣的HTML(例如)。php替換字符串並讀取完整字符串

<div> 
    <img src="http://firstsite.com/path/to/img/main.jpg" style="width: 500px; height: 400px;" /> 
</div> 

現在我儘量讓一個PHP自動改變圖像到另一個網站的路,但我也想下載的圖像,並把它們放到同一個文件夾結構。到目前爲止,我這樣做:

$input = "c:/wamp/www/primo/input12"; 
    $output = "c:/wamp/www/primo/output12"; 


    $handle = opendir($input); 
    while (($file = readdir($handle)) !== false) { 
     if($file != '.' && $file != '..') { 

      $data = file_get_contents($input . "/" . $file); 

      $data = str_replace("http://firstsite.com/", "http://secondsite.com", $data); 

      file_put_contents($output . "/" . $file, $data); 

     } 
    } 
    closedir($handle); 

這改變了路徑,但現在我需要以某種方式進入一個變量的完整路徑http://firstsite.com/path/to/img/main.jpg在我的例子,以下載圖像。

有沒有辦法讓圖像的完整路徑,而取代http://firstsite.com/這只是路徑的開始?

先謝謝你了,丹尼爾!

+0

最大的可能。在正則表達式的幫助下... – Havelock

+0

使用php domdocument –

回答

1

僅獲得圖片:

$data = file_get_contents($input . "/" . $file); 

preg_match_all('/\<img.*src=\"(.+?)\"/s', $data, $matches); 
//go through the match array and download your files 

$data = str_replace("http://firstsite.com/", "http://secondsite.com", $data); 
file_put_contents($output . "/" . $file, $data); 

獲取所有pathes:

$data = file_get_contents($input . "/" . $file); 

preg_match_all('/http\:\/\/firstsite\.com([^\s]+?)/s', $data, $matches); 
//go through the match array and download your files 

$data = str_replace("http://firstsite.com/", "http://secondsite.com", $data); 
file_put_contents($output . "/" . $file, $data); 
+0

它似乎你理解我的問題是正確的,但問題不是所有的HTML元素都是imgs,不同的路徑有不同的文件,我必須通過http://firstsite.com/搜索它們,這是路徑的開始 –

+0

看到我更新的答案 – Manu

+1

非常感謝你馬努,我已經使我的PHP與您的代碼工作,以獲得所有路徑和burgeris正則表達式。 –

1

如何:

preg_match_all('/(http:\/\/firstsite\.com\/[^\s]*)/', $data, $matches); 
+1

將在分隔符中失敗 –

+0

你是什麼意思? – bargoras

+1

我的意思是非轉義的分隔符(你在編輯之後替換) –