Href URL matching,


Href URL matching,

可能重复:
获取A元素的href属性

我试图在页面中匹配来源:

 <a href="/download/blahbal.html">

我看了这个网站上的另一个链接,并使用了regex:

   '/<a href=["'']?('/download'/[^"'''s>]+)["'''s>]?/i'

它返回页面上的所有href链接,但在某些链接上漏掉了.html。

如有任何帮助,我们将不胜感激。

感谢

首先使用此处描述的方法来检索所有href,然后可以使用regex或strpos来"过滤"那些不以/download/开头的方法
您应该使用解析器而不是regex的原因在许多其他关于堆栈溢出的文章中进行了讨论(请参阅此(。一旦解析了文档并获得了所需的href,就可以使用简单的函数将其过滤掉

一个小代码:

$dom = new DOMDocument;
//html string contains your html
$dom->loadHTML($html);
//at the end of the procedure this will be populated with filtered hrefs
$hrefs = array();
foreach( $dom->getElementsByTagName('a') as $node ) {
    //look for href attribute
    if( $node->hasAttribute( 'href' ) ) {
        $href = $node->getAttribute( 'href' );
        // filter out hrefs which don't start with /download/
        if( strpos( $href, "/download/" ) === 0 )
            $hrefs[] = $href; // store href
    }
}