0

我正在尝试<span...</span>使用以下代码在具有特定颜色#ff0000 的两个之间获取数据,但我没有得到任何数据!谁能告诉我我做错了什么?

数据示例:

<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]);
}
4

3 回答 3

3

不要使用正则表达式解析 HTML。如果你这样做,一只小猫会die()

稳定的解决方案是使用 DOM:

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

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

请注意,DOMDocument 也可以优雅地解析 HTML 片段,如下所示:

$doc->loadHTML('<span style="color: #ff0000;">get this text1</span>');
于 2013-11-02T10:07:39.740 回答
2

虽然我也建议使用 DOM 解析器,但这里是您的正则表达式的工作版本:

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

只有我所做的更改:我将分隔符从更改为/%因为斜杠也用于</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
        )

)
于 2013-11-02T10:11:47.737 回答
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 ) 
) 
于 2013-11-02T10:16:05.347 回答