我正在尝试使用preg_match_all从HTML代码块中提取所有URL。我也试图忽略所有图像。
示例 HTML 块:
$html = '<p>This is a test</p><br>http://www.facebook.com<br><img src="http://www.google.com/photo.jpg">www.yahoo.com https://www.aol.com<br>';
我使用以下方法仅尝试构建一个 URL 数组。(不是图像(
if(preg_match_all('~(?:(?:https://)|(?:http://)|(?:www'.))(?![^" ]*(?:jpg|png|gif|"))[^" <>]+~', $html, $links))
{
print_r($links);
}
在上面的示例中,$links数组应包含:
http://www.facebook.com, www.yahoo.com, https://www.aol.com
谷歌被排除在外,因为它包含.jpg图像扩展名。当我将这样的图像添加到$html时出现问题:
<img src="http://www.google.com/image%201.jpg">
百分号似乎会导致preg_match分解 URL 并提取以下"链接"。
http://www.google.com/image
知道如何只抓取不是图像的网址吗?(即使它们包含 URL 通常可能具有的特殊字符(
使用 DOM 可以识别 HTML 文档的结构。在您的情况下,识别要从中获取URL的部分。
- 使用 DOM 加载 HTML
- 使用 Xpath 从链接 href 属性中获取网址(仅当您也需要它们时(
- 使用 Xpath 从 DOM 获取文本节点
- 对文本节点值使用正则表达式来匹配网址
下面是一个实现示例:
$html = <<<'HTML'
<p>This is a test</p>
<br>
http://www.facebook.com
<br>
<img src="http://www.google.com/photo.jpg">
www.yahoo.com
https://www.aol.com
<a href="http://www.google.com">Link</a>
<!-- http://comment.ingored.url -->
<br>
HTML;
$urls = array();
$dom = new DOMDocument();
$dom->loadHtml($html);
$xpath = new DOMXpath($dom);
// fetch urls from link href attributes
foreach ($xpath->evaluate('//a[@href]/@href') as $href) {
$urls[] = $href->value;
}
// fetch urls inside text nodes
$pattern = '(
(?:(?:https?://)|(?:www'.))
(?:[^"''''s]+)
)xS';
foreach ($xpath->evaluate('/html/body//text()') as $text) {
$matches = array();
preg_match_all($pattern, $text->nodeValue, $matches);
foreach ($matches[0] as $href) {
$urls[] = $href;
}
}
var_dump($urls);
输出:
array(4) {
[0]=>
string(21) "http://www.google.com"
[1]=>
string(23) "http://www.facebook.com"
[2]=>
string(13) "www.yahoo.com"
[3]=>
string(19) "https://www.aol.com"
}