2011-07-26 86 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)或回調版本根據需要修改輸出。

相關問題