2011-07-26 88 views
1

我需要在某些html代码的一部分中找到链接,并用两个不同的绝对或基本域替换所有链接,然后在页面上链接...查找并替换网页中的所有链接使用php/javascript

我发现了很多的想法,并尝试了很多不同的解决方案..幸运在我这边没有..请帮助我! 谢谢!

这是我的代码:

<?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的行

+0

给我们一些示例HTML,并告诉我们你想如何变成。向我们展示您的编码工作!你想用PHP还是JavaScript来做? – Shef

+2

当你说“在我这边运气不好”这是否意味着你找到了x并尝试了y并没有得到它的工作?如果是这样,请显示您的尝试,我们可以从那里去 –

+0

删除了JavaScript标记,因为你正在做这个服务器端。 – scrappedcola

回答

4

var links = document.getElementsByTagName("a");将为您提供所有链接。 并通过他们这将循环:

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

我建议scrappedcola的答案,但如果你不想这样做在客户端,您可以使用正则表达式来代替:

ob_start(); 
//your HTML 

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

您可以使用引用(\ $ 1)或回调版本根据需要修改输出。

相关问题