2011-01-09 79 views
1

我在刮一個頁面,但是在我的內容被回顯之前,我想編輯鏈接。如何編輯href鏈接(刮板)

這樣做的最好方法是什麼?

我目前使用簡單的HTML DOM解析器:

// create HTML DOM 
$html = file_get_html('http://myurl.com'); 
// remove all image 
    foreach($html->find('img') as $e) 
$e->outertext = ''; 
foreach($html->find('font') as $e) 
$e->outertext = ''; 
// find all td tags with attribite align=center 
foreach($html->find('td[align=left]', 2) as $e) 
    echo $e->innertext; 

有此位的其中一個網址:

<a target="retailer" href="/cgi-bin/redirect.cgi?name=Storm%20Computers&amp;linkid=2&amp;newurl=http%3A%2F%2Fwww.stormcomputers.com.au%2Fcatalog%2Findex.php%3FcPath%3D38_364&amp;query=sandy%20bridge&amp;uca=208-0-0&amp;kwi=&amp;rpos=2" title="Storm Computers: Click to see item">$149.00</a> 

我想改變這

<a href="http%3A%2F%2Fwww.stormcomputers.com.au%2Fcatalog%2Findex.php%3FcPath%3D38_364&amp;query=sandy%20bridge&amp;uca=208-0-0&amp;kwi=&amp;rpos=2">$149.00</a> 

(即剛剛在& newurl =)

謝謝。

回答

1

我不熟悉正在使用的解析器,但類似的東西可能會起作用:

foreach ($html->find('a') as $link) { 
    $urlparts = parse_url($link->href); 
    $query = parse_str($urlparts['query'], $params); 

    if (isset($params['newurl'])) { 
     $link->href = $params['newurl']; 
    } 
} 
0

查找與DOM的鏈接。之後,只需使用爆炸來分割href字符串。

$split_href = explode('&amp;newurl=', $href); 

if(count($split_href) > 1) { 
    $newurl = $split_href[1]; 
} 

不要以爲你需要正則表達式,因爲它比較慢。

+1

只要你沒有注意到,你有`newulr`。 – thirtydot 2011-01-09 22:12:38

+0

@thirtydot。感謝您指出! – PeeHaa 2011-01-09 22:14:01

0

您可以使用正則表達式查找所有鏈接,然後使用parse_url()parse_str()重建鏈接。

例如:

if (preg_match_all('/<a href="(.+)">(.+)<\/a>/i',$html,$matches)) { 

    // at this point, $matches is a multidimensional array where 
    // index 0 is an array of all matches of the full pattern, 
    // and index 1 is an array of all captured links 
    foreach ($matches[1] as $link) { 

    // parse the link 
    if ($parsed_link = parse_url($link)) { 

     // see the documentation of parse_url() for the various 
     // array keys produced by calling it; in this case we 
     // are using the value of 'query' and passing it to 
     // parse_str() which will break a url query string 
     // into individual variables; pass $arguments as below 
     // and it will populate the result into it as an array 
     parse_str($parsed_link['query'],$arguments); 

     // now, we want the value of the 'newurl' query parameter 
     // from the original url 
     if (isset($arguments['newurl'])) { 

     $new_url = $arguments['newurl']; 

     // do whatever you want with $new_url 

     } 

    } 

    } 

} 

這當然不是要做到這一點的唯一方法,但有使用的一致性和可讀性的語言功能的一些價值。我沒有在上面的正則表達式中尋找鏈接,因此它不處理任何特殊情況。如果文檔中的鏈接格式不正確,則可能需要修改該表達式以處理多餘的空格,放錯位置的引號等。