2011-12-02 27 views
0
<h2 class="element"> 
name 
</h2> 
<div class="outerElement"> 
address 
</div> 
<h2 class="element"> 
name 
</h2> 
<div class="outerElement"> 
address 
</div> 

我需要一個正則表達式,將<h2 class="element">之間得到一切,直到下一個<h2 class="element">,所以我想出了這個:正則表達式

preg_match_all('/div class="outerElement"(.*?)div class="outerElement"/', $content, $elements); 

但由於某種原因它不工作(我有逃避雙引號或有什麼問題

+1

它不工作? – Flimzy

+0

你不應該使用正則表達式來解析HTML:http://stackoverflow.com/a/1732454/298479 – ThiefMaster

回答

2

加「S」修飾符來表達這樣的:?

'/div class="outerElement"(.*?)div class="outerElement"/s' 

這是強制多線模式匹配所必需的。

+0

仍然不工作hmm:S – randomKek

0

下面的正則表達式捕獲組1

的所有比賽。你說,你會需要遍歷一個preg_match_all比賽。

爲方便起見,這裏是空白模式的正則表達式。

(?xs)      # modes: whitespace, dot matches new line 
(?<=<h2[ ]class="element">) # is there an element h2 tag behind us 
\W*       # match any non-word char (greedy) 
(\w.*?)      # capture a word char followed by any char (lazy) 
<h2[ ]class="element"  # match the next class element 

這裏是一個使用此正則表達式,並返回拍攝組樣品preg_match_all。我已用您的示例字符串測試過它。有用。 :)

<?php 
$subject='<h2 class="element"> 
name 
</h2> 
<div class="outerElement"> 
address 
</div> 
<h2 class="element"> 
name 
</h2> 
<div class="outerElement"> 
address 
</div> 
'; 
preg_match_all('/(?xs)  # modes: whitespace, dot matches new line 
(?<=<h2[ ]class="element">) # is there an element h2 tag behind us 
\W*       # match any non-word char (greedy) 
(\w.*?)      # capture a word char followed by any char (lazy) 
<h2[ ]class="element"  # match the next class element 
/s', $subject, $all_matches, PREG_OFFSET_CAPTURE | PREG_PATTERN_ORDER); 
$size=count($all_matches[1]); 
echo "<br />*****************<br />"; 
echo "Number of Matches: ".$size."<br />"; 
echo "*****************<br />"; 
for ($i=0;$i<$size;$i++) { 
echo "Match number: ".($i+1)."<br />"; 
echo "At position: ".$all_matches[1][$i][1]."<br />"; 
echo "Captured text: ".htmlentities($all_matches[1][$i][0])."<br />"; 
} 
echo "End of Matches<br />"; 
echo "*****************<br /><br />"; 
?> 

最後,這裏是輸出:

***************** 
Number of Matches: 1 
***************** 
Match number: 1 
At position: 22 
Captured text: name </h2> <div class="outerElement"> address </div> 
End of Matches 
***************** 

如果我的理解,這就是你要找的人。