0

重複の可能性:
id が 1 番目の属性である div タグ間のテキストを取得する方法。正規表現のみ。

これがシナリオです

この正規表現を使用して、id test1、または tes2 または test3 の div タグ内のテキストを取得しています

<div id = "test1">text</div>
<div id = "test2">text</div>
<div id = "test3">text</div>

$id_value = "test1" or "test2" or "test3";
$regex = "#\<div id=\"".$id_value."\"\>(.+?)\<\/div\>#s";

私の唯一の要件は、以下のシナリオで div タグからテキストを取得することです

<div id="test" class="testing" style="color:red" etc etc .... more attributes >text</div>

つまり、id は div タグの 1 番目の属性であり、その後に n 個の属性を続けることができます。このようなタグから正規表現のみでテキストを抽出する方法。

私も試してみました

$regex = '#<div\s+.*?id="".$id_value."".*?>(.*?)</\s*div>#ims';

$id_value = "test1" の場合は div タグのテキストを返しますが、$id_value="test2" の場合はノード test1 と test2 の両方のテキスト値を返します。$id_value="test3" の場合、3 つのノードすべてのテキスト値が返されます。特定の ID のみに関連するテキスト値が必要です。正規表現のみを使用します。

助けてくださいありがとう。

4

1 に答える 1

6

HTMLの解析に正規表現を使用しないでください。代わりに、あらゆる種類のHTMLを正しく解析できるPHPのDOM拡張機能を使用してください。

例:

<?php

    $html = <<<HTML
<div id = "test1">text</div>
<div id = "test2">other text</div>
<div id = "test3">new text</div>
HTML;

    $id_list = array(
        "test1",
        "test2",
        "test3",
    );

    $doc = new DOMDocument();
    $doc->loadHTML($html);
    foreach ($id_list as $id) {
        $div = $doc->getElementById($id);
        if ($div == NULL) {
            echo "There's no element with an ID of $id<br>\n";
        }
        else {
            echo "$id's content is: " . $div->textContent . "<br>\n";
        }
    }

どうしても正規表現を使用する必要がある場合に限り、これが私が思いついたものです。

<?php

    $html = <<<HTML
<div id = "test1">text</div>
<div id = "test2">other text</div>
<div id = "test3">new text</div>
HTML;

    $id_list = array(
        "test1",
        "test2",
        "test3",
    );

    foreach ($id_list as $id) {
        $pattern = <<<REGEX
/
<div\s*                     #Opening Tag
(?:                         #Attributes before ID
    [a-z]+                  #Attribute name
    \s*=\s*                 #Equals
    (?:"[^"]*"|'[^']*')     #Attribute content
    \s*                     #Spaces?
)*                          #Many or none
(?:                         #ID Attribute
    id
    \s*=\s*
    (?:"$id"|'$id')         #Matches the ID
    \s*
)
[^>]*                       #Anything after ID
>                           #Closing Tag
([^<]*)                     #Actual content!
<\/div>
/xi
REGEX;

        preg_match_all($pattern, $html, $matches);
        var_dump($matches);
    }

注意してください、あなたがこのコードを使うならば、unh̶oly͘͘c̀h̶i͏l҉dは処女の血を泣きます。er>はそれ<centを保持することはできません手遅れです。

于 2012-08-02T17:35:40.453 に答える