2009-09-30 65 views
0

干草家伙我需要正则表达式的帮助。我想使用file_get_contents()获取页面的源代码,然后我想通过源代码循环查找所有的HREF值并将其提取到数组中。PHP的正则表达式的链接url

感谢

回答

1

你最好使用一个真正的解析器像SimpleXMLDOMDocument比正则表达式。下面是与DOM文档的例子,这将使你A元素的数组:

$doc = new DOMDocument(); 
$doc->loadHTML($str); 
$aElements = $doc->getElementsByTagName("a"); 
foreach ($aElements as $aElement) { 
    if ($aElement->hasAttribute("href")) { 
     // link; use $aElement->getAttribute("href") to retrieve the value 
    } else { 
     // not a link 
    } 
} 
+0

难道我假设$ str是从的file_get_contents返回的值()? – dotty 2009-09-30 08:52:33

+0

@dotty:是的,'$ str'是包含HTML源代码的字符串。 – Gumbo 2009-09-30 09:02:34

+0

以及我使用你的代码,但它通过了一个关于无格式标签等错误的负载。所以我做了一些挖掘,并找到了正则表达式 preg_match_all(“/ href = \”(。*?)\“/”,$ html,$ aElements); 我将如何使用它只发现http源? – dotty 2009-09-30 09:11:19