Regexp用于从HTML中提取所有链接和锚文本

Cli*_*ote 3 php regex string html-parsing

我想要一个或多个正则表达式可以:

1)获取大页面的html.

2)查找所有链接中包含的URL,例如:

<a href="http://example1.com">Test 1</a>
<a class="foo" id="bar" href="http://example2.com">Test 2</a>
<a onclick="foo();" id="bar" href="http://example3.com">Test 3</a>
Run Code Online (Sandbox Code Playgroud)

依此类推,它应该提取'href'属性中包含的url,而不管之前或之后是什么href

3)提取所有链接的锚文本,例如在上面的例子中,它应该返回'http://example1.com'和锚文本'Test 1',然后'http://example2.com'和'测试2',依此类推.

Oll*_*lie 7

<?

$dom = new DomDocument();
$dom->loadHTML($html);
$urls = $dom->getElementsByTagName('a');
Run Code Online (Sandbox Code Playgroud)

  • 这个答案是不完整的,这是一个有效的http://stackoverflow.com/questions/4423272/how-to-extract-links-and-titles-from-a-html-page-but (2认同)

Ser*_*rgi 5

你需要看一下前方并向后看.

<?php

$string = '<a href="http://example1.com">Test 1</a>
<a class="foo" id="bar" href="http://example2.com">Test 2</a>
<a onclick="foo();" id="bar" href="http://example3.com">Test 3</a>';

if(preg_match_all("|<a.*(?=href=\"([^\"]*)\")[^>]*>([^<]*)</a>|i", $string, $matches))
        {
        /*** if we find the word white, not followed by house ***/
        echo 'Found a match';
        print_r($matches);
    }
else
        {
        /*** if no match is found ***/
        echo 'No match found';
        }
?>
Run Code Online (Sandbox Code Playgroud)


小智 5

<?php
$regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>";
if(preg_match_all("/$regexp/siU", $html, $matches, PREG_SET_ORDER))
{ foreach($matches as $match)
{// $match[2] = link address
// $match[3] = link text}
}
?>
Run Code Online (Sandbox Code Playgroud)

这将提取链接和锚文本.