0

<span...</span>次のコードを使用して特定の色 #ff0000 を持つ2 つの間のデータを取得しようとしていますが、データが取得されません! 誰が私が間違っているのか教えてもらえますか?

データの例:

<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 に答える