2012-02-27 34 views
0

我正在嘗試編寫一個RegEx,它可以查找具有rel =「nofollow」屬性的網頁上的所有鏈接。你要知道,我是一個正則表達式福利局所以請不要在惡劣的我:)正則表達式:查找頁面上的所有鏈接w/nofollow

這是我走到這一步:

$link = "/<a href=\"([^\"]*)\" rel=\"nofollow\">(.*)<\/a>/iU"; 

顯然,這是非常錯誤的。任何其他屬性的鏈接或樣式稍有不同(單引號)都不會匹配。

+2

[不要。使用。正則表達式。至。解析。 HTML。](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454)...小馬,他來了。 – rdlowrey 2012-02-27 20:55:51

回答

3

你真的應該使用DOM parser用於此目的的任何基於正則表達式的解決方案將是容易出錯的這種HTML解析。考慮這樣的代碼:

$doc = new DOMDocument(); 
libxml_use_internal_errors(true); 
$doc->loadHTML($html); // loads your html 
$xpath = new DOMXPath($doc); 
// returns a list of all links with rel=nofollow 
$nlist = $xpath->query("//a[@rel='nofollow']"); 
+1

你打敗我吧! – cwallenpoole 2012-02-27 21:00:07

+0

謝謝,我已將您的示例添加到http://htmlparsing.com/php.html – 2012-02-27 22:20:04

1

試試這個:

$link = "/<(a)[^>]*rel\s*=\s*(['\"])nofollow\\2[^>]*>(.*?)<\/\\1>/i"; 
相關問題