2014-10-10 112 views
1

有人请告诉我如何使用preg_match_all捕获目标网页在同一网站上的链接列表?所有我想在搜索结果中捕捉到的链接是这样的:preg_match_all网站内的链接

<a href="http://www.facebook.com">Visit Us On Facebook</a> 
<a href="https://www.paypal.com">Pay Now</a> 

我已经花了一个小时在网上搜索:

<a href="/">Home</a> 
<a href="/about-us">About Us</a> 
<a href="/contact-us">Contact Us</a> 

的我不希望包含在结果中的链接例子并且只能找到显示网页中所有链接的示例,而不是排除在同一个网站上。

谢谢。

+0

只是链接。以下答案是我需要的帮助。 – 2014-10-10 03:47:51

回答

1

您可以尝试使用下面的正则表达式来匹配所有定位标记,其中href属性的内容以/符号开始。

<a href="(\/[^"]*)">[^<>]*<\/a> 

DEMO

代码:

<?php 
$string = <<<EOT 
<a href="/">Home</a> 
<a href="/about-us">About Us</a> 
<a href="/contact-us">Contact Us</a> 
<a href="http://www.facebook.com">Visit Us On Facebook</a> 
<a href="https://www.paypal.com">Pay Now</a> 
EOT; 
echo preg_match_all('~<a href="(\/[^"]*)">[^<>]*<\/a>~', $string, $matches); 
print_r($matches[0]); 
print_r($matches[1]); 
?> 

输出:

3Array 
(
    [0] => <a href="/">Home</a> 
    [1] => <a href="/about-us">About Us</a> 
    [2] => <a href="/contact-us">Contact Us</a> 
) 
Array 
(
    [0] =>/
    [1] => /about-us 
    [2] => /contact-us 
) 
3

下面是一个解决方案使用DOM ...

$dom = DOMDocument::loadHTML(' 
    <a href="/">Home</a> 
    <a href="/about-us">About Us</a> 
    <a href="/contact-us">Contact Us</a> 
    <a href="http://www.facebook.com">Visit Us On Facebook</a> 
    <a href="https://www.paypal.com">Pay Now</a> 
'); 

$xpath = new DOMXPath($dom); 
$nodes = $xpath->query('//a[substring(@href, 1, 1) = "/"]'); 

foreach ($nodes as $node) { 
    $links[] = $node->getAttribute('href'); 
} 
print_r($links); 

Code Demo

您可以如用preg_match()功能与DOM。

$xpath = new DOMXPath($dom); 

$xpath->registerNamespace('php', 'http://php.net/xpath'); 
$xpath->registerPHPFunctions('preg_match'); 

$nodes = $xpath->evaluate("//a[php:functionString('preg_match', '~^/~', @href)=1]"); 

foreach ($nodes as $node) { 
    $links[] = $node->getAttribute('href'); 
} 
print_r($links); 

Code Demo