2014-10-10 109 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