我想获取具有类链接的href地址


I want to grab href address which has class link

[a href="http://www.vanchosun.com/m/market_index.php?view=market"]11[/a]


[a href="test.php?view=test&cate=buysell&testid=100"class="link"]22[/a]

如何使用php preg_match_all 获取具有类链接的href

谢谢。

您可以使用这个:

$pattern = '~(?(DEFINE)(?<class>'bclass's*='s*"[^"]*?'blink'b[^"]*"))
             <a's+ [^>]*?
             (?| 'g<class> [^>]*? 'bhref's*='s*"([^"]*)"
               | 'bhref's*='s*"([^"]*)" [^>]*? 'g<class>)~xi';
preg_match_all($pattern, $code, $matches, PREG_SET_ORDER);
foreach($matches as $match) {
    echo '<br/>' . $match[1];
}

然而,peiman F.有一个很好的答案,因为DOM是这类任务的更好选择。

DOM方式:

$doc = new DOMDocument();
@$doc->loadHTML($code);
$links = $doc->getElementsByTagName('a');
foreach ($links as $link) {
    if (preg_match('~'blink'b~i', $link->getAttribute('class')))
        echo '<br/>' . $link->getAttribute('href');
}

对于这样的作业,最好使用php DOM

查看教程的简单使用方法

在所有方法列表中使用DOMElement::getAttribute方法http://www.php.net/manual/en/domelement.getattribute.php