使用SimpleHTMLDom库获取所有a href链接&;在';fly';


Get all a href links using SimpleHTMLDom library & change these on the 'fly'

我想访问html字符串中的所有a href链接,并按如下方式转换所有链接:

<a href='www.google.com'>Google</a>

会变成这样。。。

<a href='www.mysite.com/link.php?URL=www.google.com'>Google</a>

有人能建议我怎么做吗?

<?php

require_one('simple_html_dom.php');

// load the class
$html = new simple_html_dom();
// load the entire string containing everything user entered here
$string = "<html><body><base href='http://www.site.biz/clients/g/'><a href='www.google.co.uk'>Google</a><a href='http://www.yahoo.co.uk'>Yahoo</a></body></html>";
$return = $html->load($string);
$links = $html->find('a');
foreach ($links as $link) 
{
    var_dump($link);
}

?>

你试过这样的东西吗

$links = $html->find('a');
foreach ($links as $link) 
{
    if(isset($link->href))
    {
        $link->href = 'www.mysite.com/link.php?URL=' . $link->href;
    }
}
$newHTML = $html->save();
// $newHTML now contains the modified HTML