2016-07-23 122 views
0

我試圖找到一個正則表達式,可以將相對於絕對的curl'ed文檔的所有URL更改。將相對URL更改爲絕對URL Curl

我發現的其中一種方法是發佈here,但它只適用於第一個URL,並非全部。

這是代碼我使用:

$url="http://www.example.com"; 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL,$url); 
curl_setopt($ch, CURLOPT_FAILONERROR, 1);             
curl_setopt($ch, CURLOPT_DNS_USE_GLOBAL_CACHE, 0);        
curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 60);         
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);           
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);            
$result=curl_exec($ch); 
curl_close($ch); 
$result = preg_replace('~(href|src)=(["\'])(?!#)(?!http://)([^\2]*)\2~i','$1="http://www.example.com$3"', $result); 
echo $result; 

我在哪裏做錯了嗎?

編輯 只是爲了更好地解釋。我沒有一個url數組,但是我有一個從curl中收集的整個文檔,所以我需要一個preg替換方法。

+0

[Transfrom相對路徑成絕對URL使用PHP(的可能的複製http://stackoverflow.com/questions/4444475/transfrom-relative-path -into-absolute-url-using-php) –

+0

你可以用RamenChef的建議修改來實現這種方式,但可能會更加健壯,如http://stackoverflow.com/questions/4444475/transfrom-相對路徑 - 到 - 絕對網址使用的PHP。 –

+0

謝謝,但是如果我有一個url數組,那麼這個url就可以工作。在這種情況下,我需要在html文件中替換 – Luca

回答

1

我不確定爲什麼它只替換一次(也許它與反向引用有關),但是當你將它包裝在while循環中時,它應該可以工作。

$pattern = '~(href|src)=(["\'])(?!#|//|http)([^\2]*)\2~i'; 
while (preg_match($pattern, $result)) { 
    $result = preg_replace($pattern,'$1="http://www.example.com$3"', $result); 
} 

(I也稍微改變的模式。)

+0

太棒了!有用!!真的非常感謝 – Luca