在页面中查找所有href链接并替换为链接,同时保留之前的链接 - PHP。

4
我将尝试查找网页上所有的href链接,并用我的代理链接替换这些链接。
例如:
<a href="http://www.google.com">Google</a>

需要

<a href="http://www.example.com/?loadpage=http://www.google.com">Google</a>
3个回答

9
使用PHP的DomDocument解析页面。
$doc = new DOMDocument();

// load the string into the DOM (this is your page's HTML), see below for more info
$doc->loadHTML('<a href="http://www.google.com">Google</a>');

//Loop through each <a> tag in the dom and change the href property
foreach($doc->getElementsByTagName('a') as $anchor) {
    $link = $anchor->getAttribute('href');
    $link = 'http://www.example.com/?loadpage='.urlencode($link);
    $anchor->setAttribute('href', $link);
}
echo $doc->saveHTML();

在这里查看:http://codepad.org/9enqx3Rv

如果您没有HTML字符串,可以使用cUrl(文档)来获取HTML,或者您可以使用DomDocumentloadHTMLFile方法

文档


谢谢!我最终不得不这样做,因为你无法访问iframe中属性“src”的动态值。 - Glenn Dayton

0

如果您想使用jQuery替换链接,还有另一个选项:

$(document).find('a').each(function(key, element){
   curValue = element.attr('href');
   element.attr('href', 'http://www.example.com?loadpage='+curValue);

});

然而更安全的方式当然是用php来实现。


-1

我能想到的最简单的方法:

$loader = "http://www.example.com?loadpage=";
$page_contents = str_ireplace(array('href="', "href='"), array('href="'.$loader, "href='".$loader), $page_contents);

但是那可能会在包含?或&的网址上出现问题。 或者如果文档的文本(不是代码)包含href="


7
为什么不应该使用正则表达式处理HTML,或将HTML视为字符串。 - Chris Baker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接