找到页面中的所有href并用链接维护以前的链接替换 ​​- PHP

Gle*_*ton 3 php text-processing hyperlink

我正在尝试在网页上找到所有href链接,并用我自己的代理链接替换该链接.

例如

<a href="http://www.google.com">Google</a>
Run Code Online (Sandbox Code Playgroud)

需要是

<a href="http://www.example.com/?loadpage=http://www.google.com">Google</a>
Run Code Online (Sandbox Code Playgroud)

Chr*_*ker 7

使用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();
Run Code Online (Sandbox Code Playgroud)

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

如果您不具备HTML作为一个字符串,你可以使用卷曲(文档)抢HTML,或者你可以使用loadHTMLFile的方法DomDocument

文档