繁体   English   中英

使用SimpleHTMLDom库获取所有href链接,并“快速”更改它们

[英]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_once('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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM