Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
656 views
in Technique[技术] by (71.8m points)

hyperlink - Find all hrefs in page and replace with link maintaining previous link - PHP

I'm trying to find all href links on a webpage and replace the link with my own proxy link.

For example

<a href="http://www.google.com">Google</a>

Needs to be

<a href="http://www.example.com/?loadpage=http://www.google.com">Google</a>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use PHP's DomDocument to parse the page

$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();

Check it out here: http://codepad.org/9enqx3Rv

If you don't have the HTML as a string, you may use cUrl (docs) to grab the HTML, or you can use the loadHTMLFile method of DomDocument

Documentation


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...