使用php/javascript查找并替换网页中的所有链接


Find and replace all links in a web page using php/javascript

我需要在一些html代码的一部分中找到链接,并将所有链接替换为两个不同的绝对或基本域,然后是页面上的链接…

我找到了很多想法,尝试了很多不同的解决方案。运气不在我这边…请帮帮我!!谢谢你! !

这是我的代码:

<?php
$url = "http://www.oxfordreference.com/views/SEARCH_RESULTS.html?&q=android";
$raw = file_get_contents($url);
$newlines = array("'t","'n","'r","'x20'x20","'0","'x0B");
$content = str_replace($newlines, "", html_entity_decode($raw));
$start = strpos($content,'<table class="short_results_summary_table">');
$end = strpos($content,'</table>',$start) + 8;
$table = substr($content,$start,$end-$start);
echo "{$table}";
$dom = new DOMDocument();
$dom->loadHTML($table);
$dom->strictErrorChecking = FALSE;
// Get all the links
$links = $dom->getElementsByTagName("a");
foreach($links as $link) {
  $href = $link->getAttribute("href");
  echo "{$href}";
  if (strpos("http://oxfordreference.com", $href) == -1) {
  if (strpos("/views/", $href) == -1) {
     $ref = "http://oxfordreference.com/views/"+$href;
  }
  else 
      $ref = "http://oxfordreference.com"+$href;
    $link->setAttribute("href", $ref);
    echo "{$link->getAttribute("href")}";
  }
}
$table12 = $dom->saveHTML;
preg_match_all("|<tr(.*)</tr>|U",$table12,$rows);
echo "{$rows[0]}";
foreach ($rows[0] as $row){
    if ((strpos($row,'<th')===false)){
        preg_match_all("|<td(.*)</td>|U",$row,$cells);       
        echo "{$cells}";
    }
}
?>

当我运行这段代码时,我得到htmlParseEntityRef:期待';'警告的行,我加载html

var links = document.getElementsByTagName("a");将为您提供所有链接。这将循环遍历它们:

 for(var i = 0; i < links.length; i++)
    {
        links[i].href = "newURLHERE";
    }

您应该使用jQuery -它非常适合链接替换。而不是在这里解释。请看这个答案。

如何使用jQuery更改超链接的href

我推荐scrapdcola的答案,但如果你不想在客户端这样做,你可以使用regex来替换:

ob_start();
//your HTML
//end of the page
$body=ob_get_clean();
preg_replace("/<a[^>]*href=('"[^'"]*'")/", "NewURL", $body);
echo $body;

你可以使用引用('$1)或回调版本来修改你喜欢的输出