2013-12-22 57 views
2

我想抓取页面中的所有链接(href)。从页面抓取所有链接

这是我的实际代码:

preg_match_all('/href=.([^"\' ]+)/i', $content, $anchor); 

但这仅抓住域和子域(如name.name.exname.ex),但不抢的自定义网址像name.ex/name/name.php

任何人都可以请帮忙正则表达式吗?

+0

你可以列出所有的域(即.com,.org,.net等),然后preg_match_all它们。这里是所有顶级域名的wiki http://en.wikipedia.org/wiki/List_of_Internet_top-level_domains – Enijar

回答

3

我建议不要对此使用正则表达式。我建议您使用DOM解析并获得您的结果。

下面是本使用DOMXPath

$html = '<a href="name.ex/name/name.php">text</a> 
     <a href="foo.com">foobar</a>'; 

$doc = new DOMDocument(); 
$doc->loadHTML($html); 

$xpath = new DOMXPath($doc); 

foreach ($xpath->query('//a') as $link) { 
    $links[] = $link->getAttribute('href'); 
} 

print_r($links); 

Working demo

0

试试这个正则表达式:

$pattern = "/href="([^\s"]+)/"; 
preg_match_all($pattern, $content, $matches); 

if (count($matches[1]) { 
    foreach($matches[1] as $match) 
    echo $match . "<br />"; 
} 
+0

不要工作,它不会添加网址。 –

+0

添加了完整的代码,这对我来说很有用。请检查 – di3sel

0

在这里你去!

$string = "<a href='test.php/url' class=>test</a>testar <a href='test2.php/url2' class=>test</a>"; 
$pattern = "/<a(?:[^>]*)href=([^ ]*)(?:[^>]*)>/"; 

preg_match_all($pattern, $string, $matches); 

foreach($matches[1] as $match){ 
    echo $match; 
} 
1

更容易使用DOM文档的例子:

$doc = new DOMDocument(); 
@$doc->loadHTML($html); 

$linkNodes = $doc->getElementsByTagName('a'); 

foreach($linkNodes as $linkNode) { 
    $urls[] = $linkNode->getAttribute('href'); 
} 

print_r($urls);