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)
使用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
文档
DomDocument- http://php.net/manual/en/class.domdocument.phpDomElement- http://www.php.net/manual/en/class.domelement.phpDomElement::getAttribute- http://www.php.net/manual/en/domelement.getattribute.phpDOMElement::setAttribute- http://www.php.net/manual/en/domelement.setattribute.phpurlencode- http://php.net/manual/en/function.urlencode.phpDomDocument::loadHTMLFile- http://www.php.net/manual/en/domdocument.loadhtmlfile.php| 归档时间: |
|
| 查看次数: |
2728 次 |
| 最近记录: |