php正则表达式匹配特定的url模式 [英] php regular expression to match specific url pattern

查看:61
本文介绍了php正则表达式匹配特定的url模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从几百个 html 页面中抓取"几百个网址.

I'd like to "grab" a few hundred urls from a few hundred html pages.

模式:

<h2><a href="http://www.the.url.might.be.long/urls.asp?urlid=1" target="_blank">The Website</a></h2>

推荐答案

这里是如何正确使用原生 DOM 扩展

Here is how to do it properly with the native DOM extensions

// GET file
$doc = new DOMDocument;
$doc->loadHtmlFile('http://example.com/');

// Run XPath to fetch all href attributes from a elements
$xpath = new DOMXPath($doc);
$links = $xpath->query('//a/@href');

// collect href attribute values from all DomAttr in array
$urls = array();
foreach($links as $link) {
    $urls[] = $link->value;
}
print_r($urls);

请注意,上面也会找到相对链接.如果您不希望那些将 Xpath 调整为

Note that the above will also find relative links. If you don't want those adjust the Xpath to

'//a/@href[starts-with(., "http")]'

请注意,使用 Regex 匹配 HTML 是通往疯狂之路.正则表达式匹配字符串模式并且对 HTML 元素和属性一无所知.DOM 确实如此,这就是为什么对于超出从标记匹配超平凡字符串模式的每种情况,您应该更喜欢它而不是 Regex.

这篇关于php正则表达式匹配特定的url模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆