在抓取網頁的 html 后,我需要有條件地替換文本以更正資源和媒體的鏈接。我需要通過將 'href="/' 替換為 'href="http://example.com/' 來替換本地鏈接,以便鏈接正常工作,但同時排除像 'href="//' 這樣的內容鏈接到不使用“http:/https:”的異地資源以實現與 SSL 兼容和不與 SSL 兼容。所以...如果 'href="/' 或 'href=/'但如果 'href="//' 或 'href=//' 則不然這并沒有取代任何東西... $html = str_replace('href="?/(?!/)', $url, $html);同時我首先替換//: $html = str_replace('href="//', 'href="https://', $html);
$html = str_replace('href=//', 'href=https://', $html);
1 回答

米脂
TA貢獻1836條經驗 獲得超3個贊
您需要用于preg_replace正則表達式替換,而不是str_replace:
$tests = array("<a href=\"/", "<a href=/", "<a href=\"//", "<a href=//");
$pattern = '/href=("?)\/(?!\/)/';
foreach ($tests as $test) {
echo preg_replace($pattern, "href=\\1http://example.com/", $test);
echo "\n";
}
輸出:
<a href="http://example.com/
<a href=http://example.com/
<a href="//
<a href=//
- 1 回答
- 0 關注
- 130 瀏覽
添加回答
舉報
0/150
提交
取消