2013-11-02 26 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) 
) 
相关问题