hlfshy hlfshy - 1 year ago 72
HTML Question

How to get URL's in all Tag 'a' from a Webpage(PHP)?My code worked not as expect

i trying to get all URL's in Tag 'a' from Webpage

for example

$text = file_get_contents ( 'http://stackoverflow.com/' );
$preg = '/<a.+?href=(http:\/\/\w+?\..+?).*?>.+?<\/a>/';
echo '<pre>';
echo '</pre>';

after that,i think the href= maybe "..." or '...',so change the Regex to


i found the transfer protocol maybe http or https,i change the Regex to


but it still worked not as expect.

Answer Source

The answer is to stop trying to parse HTML with regular expressions and learn how to use an XML parser, like the convenient DOM API in PHP.

$html = <<<'HTML'
<a href="http://foobar.baz/firstlink">first link here</a>
<a href='https://www.foobar.quix/secondlink'>second link here</a>
<a href='//www.foobar.quix/thirdlink'>thirdlink here</a>
<a href=/fourthlink>fourthlink here</a>
$dom = new DOMDocument;
$nodes = $dom->getElementsByTagName("a");

foreach($nodes as $node) {
    echo $dom->saveHTML($node), "\n";


<a href="http://foobar.baz/firstlink">first link here</a>
<a href="https://www.foobar.quix/secondlink">second link here</a>
<a href="//www.foobar.quix/thirdlink">thirdlink here</a>
<a href="/fourthlink">fourthlink here</a>

Now it doesn't matter what's in the anchor tag or how it's formulated. Whether it has single quotes or double quotes or no quotes at all or whether it's starts with http or https or whatever the case may be. You can always get to the href attribute value from $node->getAttribute('href') easily from inside that loop.

foreach($nodes as $node) {
    echo $node->getAttribute("href"), "\n";


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download