2012-02-23 120 views
1

我試圖學習如何從php頁面中獲取數據,我可以看到如何獲取標籤之間的所有內容,但有沒有辦法獲取標籤內的標籤內容?是否可以嵌套preg_match?

在下面的html中,我將如何訪問其中一個粗體跨度的內容,例如第二個?

<html> 
<div class="padding10"> 
<span class="bold"></span> 
<span class="bold"></span> 
<span class="bold"></span> 
<span class="bold"></span> 
</div> 
</html> 

我嘗試以下,這讓我獲得padding10 div的內容,但我不知道如何去任何進一步得到了大膽的跨越。我試過的所有東西都不起作用。

//gets all 
$file_string = file_get_contents('http://www.test.com/index.html'); 

//gets all in padding10 div 
preg_match('/<div class="padding10">(.*)<\/div>/si', $file_string, $padding_10); 

//gets all bold spans on padding10 div?? 
preg_match_all('/<span class="bold">(.*)<\/span>/i', $padding_10[1], $spans_10); 

我開始從我讀什麼,這是可能是想了解這個錯誤的或低效的方式,但任何幫助將是巨大的實現。謝謝。

+0

http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – 2012-02-23 03:19:35

+0

這應該讓你開始:http://stackoverflow.com/questions/1898905/recursive-regular-expression-to-process-nested-strings-enclosed-by-and – yoda 2012-02-23 03:19:43

+0

[你嘗試過一個HTML解析器嗎?](http://stackoverflow.com/questions/1732348/regex-match -open-tags-except-xhtml-self-contained-tags/1732454#1732454) – deceze 2012-02-23 03:19:51

回答

2

也許phpQuery可以提供幫助嗎? 「基於jQuery JavaScript庫的服務器端,可鏈接,CSS3選擇器驅動的文檔對象模型(DOM)API」。這將允許您從解析的HTML文檔中選擇內容。這可能更適合HTML解析/遍歷,而不是「手動」執行正則表達式。

http://code.google.com/p/phpquery/

+0

抱歉,從未真正使用過PHP,是否像下載和添加一樣簡單:require_once('phpQuery-onefile.php'); – mao 2012-02-23 03:34:11

4

你試過this

+0

不,但我現在正在看,謝謝 – mao 2012-02-23 03:34:40

+0

歡迎!它是有據可查的,並且易於實施。 – dee 2012-02-23 03:38:26

+0

這簡單得多。它適用於我,代碼以防萬一有人發現它有用:foreach($ html-> find('div [class = padding10]')as $ element); foreach($ element-> find('span [class = bold]')as $ e) echo $ e-> innertext。 '
'; – mao 2012-02-23 03:57:08

相關問題