使用 PHP 替换 href=“ ” 之间的特定完整链接


Replace Specifc Full Links Between href=" " Using PHP

我尝试搜索相关答案,但找不到适合我特定需求的东西。在我的一个wordpress网站上,我在1000多篇文章中有相当多的会员链接 - 它们都以相同的URL格式和子域结构开头:

http://affiliateprogram.affiliates.com/

但是,在初始 url 格式之后,查询字符串会为每个单独的 url 附加更改,以便将访问者引导至目标网站上的特定页面。

正在寻找一些东西,可以扫描一串 html 代码(文章正文(以查找包含上述特定域的所有 href 链接,然后将整个链接(无论附加的任何查询字符串(替换为我选择的另一个标准链接。

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);

人们可能会过来推荐一种冗长的 domdocument 方法,但对于这样的任务来说,这可能是矫枉过正的。