2011-07-25 81 views

回答

3

通常你最好關閉使用DOM文檔的所有HTML/XML解析:

$doc = new DomDocument(); 
$doc->loadHTML('<html>...</html>'); 
foreach($dom->getElementsByTagName('td') as $node) 
{ 
    echo $node->nodeValue; 
} 

爲了得到一個TD與寬度= 「183」,那麼你可以使用DomXPath

$xpath = new DOMXpath($dom); 

$elements = $xpath->query("*/td[@width='183']"); 

foreach($elements as $node) 
{ 
    echo $node->nodeValue; 
} 
+0

但也有很多'td'我想'183''寬度'正好 – user850019

+0

@user看到更新 – cwallenpoole

+0

你不能給我一種方式使用'preg_match',因爲有另一件事,我會使用'preg_match',所以如果你給我一個代碼,對我來說通過這個來學習會更好。 – user850019

1

好,最好不要與preg_match ...更好地與:

php > $xml = new SimpleXmlElement('<root><td width="183">A</td><td width="182">B</td><td width="181">C</td></root>'); 
php > foreach($xml->xpath('//td[@width=183]') as $td) echo (string)$td,"\n"; 
A 

或類似。

如果你絕對要...:

php > preg_match_all('/<td width="183">(.*?)<\\/td>/', '<root><td width="183">A</td><td width="182">B</td><td width="181">C</td></root>', $matches); 
php > var_dump($matches); 
array(2) { 
    [0]=> 
    array(1) { 
    [0]=> 
    string(22) "<td width="183">A</td>" 
    } 
    [1]=> 
    array(1) { 
    [0]=> 
    string(1) "A" 
    } 
} 

反正......我告訴你,這正則表達式的方法是容易破碎,不推薦。

編輯:我解決了從開始就不清楚的「只有183」 - 部分。

+1

與帶有loadHTML方法的DOM不同,當它無效時,SimpleXML將失敗XHTML – Gordon

1

使用preg_match_all(),並檢查該示例中出:

<?php 
// The \\2 is an example of backreferencing. This tells pcre that 
// it must match the second set of parentheses in the regular expression 
// itself, which would be the ([\w]+) in this case. The extra backslash is 
// required because the string is in double quotes. 
$html = "<b>bold text</b><a href=howdy.html>click me</a>"; 

preg_match_all("/(<([\w]+)[^>]*>)(.*?)(<\/\\2>)/", $html, $matches, PREG_SET_ORDER); 

foreach ($matches as $val) { 
    echo "matched: " . $val[0] . "\n"; 
    echo "part 1: " . $val[1] . "\n"; 
    echo "part 2: " . $val[2] . "\n"; 
    echo "part 3: " . $val[3] . "\n"; 
    echo "part 4: " . $val[4] . "\n\n"; 
} 
?> 

上面的示例將輸出:

匹配:粗體文本
第1部分:<b>
第2部分:乙
第3部分:粗體文本
第4部分:</b>

匹配:點擊我
第1部分:<a href=howdy.html>
第2部分:一個
第3部分:按我
第4部分:</a>

正如你可以,你可以在$回聲$ VAL [3]來獲得html標籤內部是什麼。我從這個鏈接中得到了例子。

http://www.php.net/manual/en/function.preg-match-all.php