2013-11-02 27 views
0

我想使用以下代碼獲取具有特定顏色#ff0000的兩個<span...</span>之間的數據,但我沒有收到數據!任何人都可以告訴我我做錯了什麼?數據如何使用preg匹配所有的<span ...</span>之間的數據?

例如:

<span style="color: #ff0000;">get this text1</span> | 
<span style="color: #ff0000;">get this text2</span> | 
<span style="color: #ff0000;">get this text3</span> | 
<span style="color: #ff0000;">get this text4</span> | 

PHP代碼:

if(preg_match_all("/<span style=\"color: #ff0000;\">(.*?)</span>/i", $code2, $epititle)) 
{ 
print_r($epititle[2]); 
} 
+0

''/ (*? )<\/span>/s'' –

回答

2

雖然我也建議使用DOM解析器,這裏的您的正則表達式的工作版本:

if(preg_match_all("%<span style=\"color: #ff0000;\">(.*?)</span>%i", $code2, $epititle)) 

只有我所做的更改:我更改了分隔符。ERS從/%因爲斜線也在</span>

完整輸出(print_r($epititle);)是用於:

Array 
(
    [0] => Array 
     (
      [0] => <span style="color: #ff0000;">get this text1</span> 
      [1] => <span style="color: #ff0000;">get this text2</span> 
      [2] => <span style="color: #ff0000;">get this text3</span> 
      [3] => <span style="color: #ff0000;">get this text4</span> 
     ) 

    [1] => Array 
     (
      [0] => get this text1 
      [1] => get this text2 
      [2] => get this text3 
      [3] => get this text4 
     ) 

) 
+0

非常感謝所有。 Reeno你的解決方案效果很好:-) – user1788736

3

不要用正則表達式解析HTML。如果你這樣做,一隻小貓將die();

穩定的解決方案是使用DOM:

$doc = new DOMDocument(); 
$doc->loadHTML($html); 

foreach($doc->getElementsByTagName('span') as $span) { 
    echo $span->nodeValue; 
} 

注意DOM文檔可以正常解析HTML片段,以及像這樣:

$doc->loadHTML('<span style="color: #ff0000;">get this text1</span>'); 
+1

這不起作用,因爲沒有名爲getElementsBy的方法NodeName()' - 你可能想使用'getElementsByTagName'來代替。 –

+0

+1使用DOMDocument – havana

+0

@AmalMurali和哈瓦那。感謝您解決命名問題! :) – hek2mgl

0
$code2 = '<span style="color: #ff0000;">get this text1</span>'; 

preg_match_all("/<span style=\"color: #ff0000;\">(.*?)<\/span>/i", $code2, $epititle); 

print_r($epititle); 

輸出

Array ( 
    [0] => Array ( [0] => get this text1) 
    [1] => Array ([0] => get this text1) 
) 
相關問題