亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 if/not 有條件地 str_replace 文本

如何使用 if/not 有條件地 str_replace 文本

PHP
互換的青春 2023-08-19 16:22:58
在抓取網頁的 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=//

演示


查看完整回答
反對 回復 2023-08-19
  • 1 回答
  • 0 關注
  • 130 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號