2010-12-18 69 views
0

一個html標籤內容我有一些HTML代碼,其中包含這些:如何抓住與preg_match_all

<table class="qprintable2" width="100%" cellpadding="4" cellspacing="0" border="0"> 
content goes here ! 
</table> 

我有這個功能來匹配裏面

function getTextBetweenTags($string, $tagname) 
{ 
    $pattern = "/<table class=\"class1\" width=\"100%\" cellpadding=\"4\" cellspacing=\"0\" border=\"0\">(.*?)<\/$tagname>/"; 
    preg_match_all($pattern, $string, $matches); 
    return $matches[1]; 
} 

的標籤,但它不有,所以我會高度讚賞,如果你能給我一個很好的模式:(

+0

可能重複http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml -self-contained-tags) – 2010-12-18 02:34:47

+1

AWESOMEST REGEX HTML PARSER EVAR:http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – 2010-12-18 02:36:03

回答

3

你應該避免這個,但你可以使用像這樣的正則表達式:

preg_match('#<table[^>]+>(.+?)</table>#ims', $str); 

各種招數這裏:

  • /ims修改,這樣也使用#代替/爲匹配新行,不區分大小寫,多選項(^和$)
  • 「」封閉正則表達式,所以你不必逃避html結束標記
  • 使用[^>]+使其不明確,並避免列出單個html屬性(更可靠)

儘管這是一個正則表達式可以正常工作的情況,但一般的共識是您應該使用QueryPath或phpQuery(或類似)來提取html。它也MUCHO簡單:

qp($html)->find("table")->text(); //would return just the text content 
[除XHTML自足標籤的正則表達式匹配開放標籤(的