2011-04-12 34 views
0

我想從與從下面這些標籤「../category/」開頭的網頁獲取網址:PHP正則表達式來獲取特定的URL

<a href="../category/product/pc.html" target="_blank">PC</a><br> 
<a href="../category/product/carpet.html" target="_blank">Carpet</a><br> 

任何建議將是非常讚賞。

謝謝!

+0

並與他們做什麼? – mcgrailm 2011-04-12 14:37:53

回答

5

不需要正則表達式。與DOM的簡單XPath查詢就足夠了:

$dom = new DOMDocument; 
$dom->loadHTML($html); 
$xpath = new DOMXPath($dom); 

$nodes = $xpath->query('//a[starts-with(@href, "../category/")]'); 
foreach ($nodes as $node) { 
    echo $node->nodeValue.' = '.$node->getAttribute('href').PHP_EOL; 
} 

會打印:

PC = ../category/product/pc.html 
Carpet = ../category/product/carpet.html 
+0

很棒的建議! – 2011-04-12 14:46:33

+0

對不起,但我沒有使用過,我想從鏈接中獲取內容。類似於「http://www.example.com/p/carpet.html」。我將如何將其添加到代碼? – user704278 2011-04-13 02:28:21

+0

@ user704278:如果你想重寫URL,只需要:'$ new_href ='example.com/p /'。basename($ node-> getAttribute('href'));' – netcoder 2011-04-13 15:01:02

0

../category/字符串此正則表達式搜索:

preg_match_all('#......="(\.\./category/.*?)"#', $test, $matches); 

所有的文本文字被用於匹配。您可以替換.....以使其更具體。只有\.需要轉義。 .*?尋找一個可變長度的字符串。並且()捕獲匹配的路徑名稱,所以它出現在$匹配中。手冊解釋了其餘的語法。 http://www.php.net/manual/en/book.pcre.php