2013-10-04 223 views
1

我需要更換curl拍攝的網頁中的網址,並添加圖像和鏈接的正確鏈接。我的PHP代碼捲曲是:preg_replace改變鏈接從href

<?php 

$result = '<a href="http://host.org"><img src="./sec.png"></a> 
<link href="./styles.css" rel="alternate stylesheet" type="text/css" /> 
<script type="text/javascript" src="./style.js"></script>'; 

echo $result; 
if (!preg_match('/src="https?:\/\/"/', $result)) { 
     $result = preg_replace('/src="(http:\/\/([^\/]+)\/)?([^"]+)"/', "src=\"http://google.com/\\3\"", $result); 
    } 
echo $result; 
if (!preg_match('/href="https?:\/\/"/', $result)) { 
     $result = preg_replace('/href="(http:\/\/([^\/]+)\/)?([^"]+)"/', "href=\"http://google.com/\\3\"", $result); 
    } 
echo $result; 

?> 

輸出是:

//original links 
<a href="http://host.org"><img src="./sec.png"></a> 
<link href="./styles.css" type="text/css" /> 
<script src="./style.js"></script><br /> 

//fixed SRC path 
<a href="http://host.org"><img src="http://google.com/./sec.png"></a> 
<link href="./styles.css" type="text/css" /> 
<script src="http://google.com/./style.js"></script> 

//fixed HREF path 
<a href="http://google.com//google.com/./sec.png"></a> 
<link href="http://google.com/./styles.css" type="text/css" /> 
<script src="http://google.com/./style.js"></script> 

但是,當鏈接是「一」,它切割所有鏈接,只留下href的值。

//from 
<a href="http://host.org"><img src="./sec.png"></a> 
//to src fix: 
<a href="http://host.org"><img src="http://google.com/./sec.png"></a> 
//ERRRROR when href fix make : 
<a href="http://google.com//google.com/.sec.png"></a> 

任何機構都可以幫助解決它。謝謝

回答

4

從你的正則表達式中刪除此不必要的部分:([^ /] +)/

它會導致你的正則表達式來一路匹配到URL中的一個標籤。

代碼:

$result = preg_replace('/src="(http:\/\/)?([^"]+)"/', "src=\"http://google.com/\\2\"", $result); 
$result = preg_replace('/href="(http:\/\/)?([^"]+)"/', "href=\"http://google.com/\\2\"", $result); 

結果:

<a href="http://google.com/host.org"><img src="http://google.com/./sec.png"></a> 
<link href="http://google.com/./styles.css" rel="alternate stylesheet" type="text/css" /> 
<script type="text/javascript" src="http://google.com/./style.js"></script> 

但是!我認爲你真正想要的是一種用絕對網址取代相關網址的方法。 對於您可以使用這些正則表達式(這樣,你可以跳過如果-檢查):

$result = preg_replace('/src="(?!http:\/\/)([^"]+)"/', "src=\"http://google.com/\\1\"", $result); 
$result = preg_replace('/href="(?!http:\/\/)([^"]+)"/', "href=\"http://google.com/\\1\"", $result); 
+0

謝謝!!!!!! – Eugenia