2013-03-07 43 views
5

我如何通過preg_match找到此div的內容<div class="lot-price-block">preg_match查找特定div與類別之間的內容

我做了這樣的事情,但我不能得到什麼:

$value=preg_match_all('/<div class=\"lot\-price\-block\">(.*)<\/div>/',$file_contents,$estimates); 
+0

'的print_r($估計)' – str 2013-03-07 13:19:27

+0

的問題是,查詢任何回報....我知道如何來顯示它 – 2013-03-07 13:22:31

+2

使用正則表達式解析HTML的第一條規則:不要使用正則表達式解析HTML] (http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) – SDC 2013-03-07 13:31:25

回答

14

首先,通過使用?運算符使您的正則表達式變得更加貪婪。這將確保你不會得到更多,然後你認爲你會得到。接下來的事情是/s運算符在表達式結尾。我假設你解析了一個包含許多新行字符「\n」的HTML文件。

$value=preg_match_all('/<div class=\"lot\-price\-block\">(.*?)<\/div>/s',$file_contents,$estimates); 
+0

這個作品謝謝你;-) – 2013-03-07 13:43:29

+0

快樂幫助 – 2013-03-07 13:50:36

+0

但如何從參考div像內容

Hello how are you
我想要使用獨特的preg_match,不應該重複。現在提取'你好,'你是如何'字符串使用ID和類都。 – 2015-05-06 08:11:42

0

試試這個:

$file_contents = '<div class="lot-price-block">Test content</div>'; 

$value=preg_match_all('/<div\s*class="lot\-price\-block"\s*>(?P<content>.*)<\/div>/',$file_contents,$estimates); 

echo "<pre>"; 
print_r($estimates); 

你會得到所有匹配的內容print_r($estimates['content']);

+0

編輯的代碼,請現在檢查 – 2013-03-07 13:32:12

+0

但如何從參考股如我的內容

Hello how are you
我想使用獨特的preg_match,不應該重複。現在提取'你好,'你是如何'字符串使用ID和類都。 – 2015-05-06 08:16:06