使用preg_match_all从上下文获取链接

时间:2012-02-24 16:04:07

标签: php regex preg-match-all

我正试图从文本中获取所有链接及其内容,但我的问题是链接可能还有其他属性,如类或ID。这个模式会是什么?

到目前为止我尝试的是:

/<a href="(.*)">(.*)<\/a\>/

谢谢你, 拉杜

2 个答案:

答案 0 :(得分:3)

正如您对问题的评论所述,请避免使用HTML正则表达式。 正确方法是使用DOMDocument

$dom = new DOMDocument;
$dom->load($html);

$xpath = new DOMXPath($dom);
$links = $xpath->query('//*/a');

foreach ($links as $link) {
    /* do something with this */
    $href = $link->getAttribute('href');
    $text = $link->nodeValue;
}

修改

An even better answer on the subject

答案 1 :(得分:0)

这应该这样做:

/<a .*?href="(.*?)"[^>]*>([^<]*)<\/a>/i

Read this并查看您是否仍想使用它。