2011-06-16 18 views
0

我做一些PHP HTML解析,這是代碼我現在所擁有的正則表達式的問題與多個結果

function get_tag($htmlelement,$attr, $value, $xml ,$arr) { 
    $attr = preg_quote($attr); 
    $value = preg_quote($value); 
    if($attr!='' && $value!='') 
    { 
    $tag_regex = '/<'.$htmlelement.'[^>]*'.$attr.'="'.$value.'">(.*?)<\\/'.$htmlelement.'>/si'; 
    preg_match($tag_regex,$xml,$matches); 
    } 
    else 
    { 
    $tag_regex = '/'.$htmlelement.'[^>]*"(.*?)\/'.$htmlelement.'/i'; 
    preg_match_all($tag_regex,$xml,$matches); 
    } 
    if($arr) 
     return $matches; 
    else 
     return $matches[1]; 
} 
$htmlcontent = file_get_contents("doc.html"); 
$extract = get_tag('tbody','id', 'open', $htmlcontent,false); 

$trows = get_tag('tr','', '', $htmlcontent,false); 

擁有該行被解析/在$提取物中的內容都可以在這裏http://pastebin.com/ydiAdiuC查看。

基本上,我正在閱讀html內容並從html獲取標籤tbody。現在我想要在tbody中獲取每個tr和td值並將其用於我的頁面。任何想法如何使用,我想我沒有使用正確的方法來實現preg_match_all。

+1

相關答案:http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – arnemart 2011-06-16 12:53:46

回答

7

爲此使用PHP的DOM Parsers。不是正則表達式。

一個快速的方法:

  • 負載在HTML
  • 獲取tbody標籤。
  • 獲取tr標籤內。
+0

+1使用的解析器,不是正則表達式 – 2011-06-16 12:52:46

+0

哪裏是bobince鏈接 – dynamic 2011-06-16 12:54:34

+0

你能給我一個短代碼嗎? html標籤沒有正確關閉,我無法控制html內容。 – Joe 2011-06-16 13:02:32