2012-07-31 38 views
0

即使我試圖只得到的的preg_match讓我整個頁面的內容,而不是特定的div

<div class="description">...</div> 

它返回我這個特定的div下的所有內容。我怎樣才能得到它之間的內容?

$file_string = file_get_contents(''); 

preg_match('/<div class="description">(.*)<\/div>/si', $file_string, $description); 
$description_out = $description[1]; 

echo $description_out; 
+1

我建議你使用類似[phpQuery](http://code.google.com/p/phpquery/)而不是正則表達式 - 它更易於使用,並且具有更高的內存效率。 – Alfo 2012-07-31 14:50:31

+0

或者,而不是添加一個額外的抽象層,只是用'DOMDocument'或類似 – 2012-07-31 14:58:40

回答

2

您應該使用non-greedy匹配。將(.*)更改爲(.*?)

此外,儘可能避免使用正則表達式來解析HTML。

+0

@JohnBilly解析HTML以擴展Mark的答案,您應該使用DOM http://php.net/manual/en/book .dom.php解析你的HTML。 – Matt 2012-07-31 14:51:23

0

這是另一種方法,當您想要使用PHP DOMDocument類獲取/閱讀PHP中的HTML元素時指示。

<?php 
// string with HTML content 
$strhtml = '<!doctype html> 
<html> 
<head> 
<meta charset="utf-8" /> 
<title>Document Title</title> 
</head> 
<body> 
<div id="dv1">www.MarPlo.net</div> 
<div class="description">http://www.coursesweb.net</div> 
</body></html>'; 

// create the DOMDocument object, and load HTML from a string 
$dochtml = new DOMDocument(); 
$dochtml->loadHTML($strhtml); 

// gets all DIVs 
$divs = $dochtml->getElementsByTagName('div'); 

// traverse the object with all DIVs 
foreach($divs as $div) { 
    // if the current $div has class="description", gets and outputs content 
    if($div->hasAttribute('class') && $div->getAttribute('class') == 'description') { 
    $cnt = $div->nodeValue; 
    echo $cnt. '<br/>'; 
    } 
} 
?> 

您可以在php.net上找到關於DOMDocument的文檔。

相關問題