簡體   English   中英

preg_replace更改來自href的鏈接

[英]preg_replace change link from href

我需要替換curl帶走的頁面中的URL,並向圖像和鏈接添加正確的鏈接。 我的PHP curl代碼是:

<?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>

但是,當鏈接為“ a”時,它將剪切所有鏈接並僅保留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>

任何身體都可以幫助修復它。 謝謝

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

它使您的正則表達式始終與下一個標記中的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>

但! 我認為您真正想要的是一種用絕對URL替換相對URL的方法。 為此,您可以使用以下正則表達式(與此同時,您可以跳過if-checks):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM