2011-11-16 144 views
2

我想用正則表達式從HTML文件中提取多個URL。 該文件中還有其他URL,做我唯一的模式是「tableentries」。和 「」PHP正則表達式HTML - 提取URL

HTML代碼示例:

<tr class="tableentries2"> 
    <td> 
    <a href="http://example.com/all-files/files/00000000789/">Click Here</a> 
    </td> 

PHP我寫道:

$html = "value of the code above" 
if(preg_match_all('/<td>.*</td>/', $html, $match)){ 
foreach($match[0] as $x){ 

echo $x . "<br>"; 

}} 
+0

你的問題是什麼呢?這段代碼給你帶來了什麼?爲什麼它不起作用? – talnicolas

+0

您的HTML屬性缺少引號。 'tr class =「tableentries2」> ... ' (edited your question) –

+0

Maybe be use an DOM parser like http://simplehtmldom.sourceforge.net/ –

回答

4

你真的不應該使用正則表達式來解析HTML。 DOMDocument實際上非常容易使用這種類型的東西。這裏是一個簡單的例子。

<?php 
error_reporting(E_ALL); 
$html = " 
<table> 
    <tr> 
     <td> 
      <a href='http://www.test1-1.com'>test1-1</a> 
     </td> 
     <td> 
      <a href='http://www.test1-2.com'>test1-2</a> 
     </td> 
     <td> 
      <a href='http://www.test1-3.com'>test1-3</a> 
     </td> 
    </tr> 
    <tr> 
     <td> 
      <a href='http://www.test2-1.com'>test2-1</a> 
     </td> 
     <td> 
      <a href='http://www.test2-2.com'>test2-2</a> 
     </td> 
     <td> 
      <a href='http://www.test2-3.com'>test2-3</a> 
     </td> 
    </tr> 
</table>"; 

$DOM = new DOMDocument(); 
//load the html string into the DOMDocument 
$DOM->loadHTML($html); 
//get a list of all <A> tags 
$a = $DOM->getElementsByTagName('a'); 
//loop through all <A> tags 
foreach($a as $link){ 
    //echo out the href attribute of the <A> tag. 
    echo $link->getAttribute('href').'<br />'; 
} 
?> 

這將輸出:

http://www.test1-1.com 
http://www.test1-2.com 
http://www.test1-3.com 
http://www.test2-1.com 
http://www.test2-2.com 
http://www.test2-3.com 
+1

問題是網頁上還有其他的URL,所以我唯一的模式是」tableentries「,開始和」「之後的URL.Thanks的幫助! –

+0

你怎麼也抓住鏈接的test1-2標題? – thevoipman

+0

@thevoipman有一個你可以使用的nodeValue屬性,像'$ link-> nodeValue'。是一個例子:http://codepad.viper-7.com/JBsfP1 –

0
<?php 
preg_match_All("#<a\s[^>]*href\s*=\s*[\'\"]??\s*?(?'path'[^\'\"\s]+?)[\'\"\s]{1}[^>]*>(?'name'[^>]*)<#simU", $html, $hrefs, PREG_SET_ORDER); 

foreach ($hrefs AS $urls){ 
print $urls['path']."<br>"; 
} 
?>