簡體   English   中英

使用PHP替換href =“”之間的特定完整鏈接

[英]Replace Specifc Full Links Between href=“ ” Using PHP

我嘗試搜索相關答案,但找不到適合我特定需求的東西。 我的一個wordpress網站上有成千上萬的文章有很多會員鏈接-所有鏈接都以相同的url格式和子域結構開頭:

http://affiliateprogram.affiliates.com/

但是,在初始URL格式之后,查詢字符串將針對每個單獨的URL附加更改,以便將訪問者發送到目標網站上的特定頁面。

我正在尋找一種可以掃描包括上面特定域的所有href鏈接的html代碼字符串(文章正文),然后用我選擇的另一個標准鏈接替換“全鏈接”(無論附加查詢字符串如何)。

href="http://affiliateprogram.affiliates.com/?random=query_string&page=destination"

被替換為

href="http://www.mylink.com"

理想情況下,我希望通過php進行此操作,因為我有基本的了解,但是如果您有任何其他建議,我將不勝感激。

提前致謝。

<?php

$html = 'href="http://affiliateprogram.affiliates.com/?random=query_string&page=destination"';

echo preg_replace('#http://affiliateprogram.affiliates.com/([^"]+)#is', 'http://www.mylink.com', $html);

?>

http://ideone.com/qaEEM

使用正則表達式,例如:

href="(https?:\/\/affiliateprogram.affiliates.com\/[^"]*)"

$data =<<<EOT
  <a href="http://affiliateprogram.affiliates.com/?random=query_string&page=destination">bar</a>
  <a href="http://stackoverflow.com/questions/8490284/replace-specifc-full-links-between-href-using-php">foo</a>
  <a name="zz" href="http://affiliateprogram.affiliates.com/?query=random&page=destination&string">baz</a>
EOT;

echo (
  preg_replace (
    '#href="(https?://affiliateprogram.affiliates.com/[^"]*)"#i',
    'href="http://www.mylink.com"',
    $data
  )
);

輸出

<a href="http://www.mylink.com">bar</a>
<a href="http://stackoverflow.com/questions/8490284/replace-specifc-full-links-between-href-using-php">foo</a>
<a name="zz" href="http://www.mylink.com">baz</a>
$a = '<a class="***" href="http://affiliateprogram.affiliates.com/?random=query_string&page=destination" attr="***">';

$b = preg_replace("/<a([^>]*)href=\"http:\/\/affiliateprogram\.affiliates\.com\/[^\"]*\"([^>]*)>/", "<a\\1href=\"http://www.mylink.com/\"\\2>", $a);

var_dump($b); // <a class="***" href="http://www.mylink.com/" attr="***">

這很簡單,因為查詢字符串只需要一個占位符。 .*? 通常會這樣做,但是您可以通過匹配任何不是雙引號的內容來使其更加具體:

$html =
preg_replace('~ href="http://affiliateprogram\.affiliates\.com/[^"]*"~i',
              ' href="http://www.mylink.com"', $html);

人們可能會四處走動,並建議使用方法,但這對於這樣的任務可能是過大了。

暫無
暫無

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

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