simple html dom:通过匹配标签内的文本来查找元素

simple html dom: find an element by matching the text inside the tag

我想找到没有 class 或 ID 的特定 h4 标签。我想找到文本旁边的 h4 标签在里面:
正如您在下面看到的 h4 标签位于块标签内,但块标签编号对于每个产品都是不同的,例如其中一些没有价格。所以如果我这样做 $html->find('block[2]') 如果没有任何价格,它会给我显示颜色。
所以我想说如果 h4 inner text = 'Price:' 告诉我 ,163 是在 .block 标签内。好的?

目标HTML:

<div class="article" id="article">

    <div class="block">
        <h4>First name and last name:</h4>
         name name
     </div>

     <div class="block">
         <h4>Price:</h4>
          ,163
           <span>(50% off)</span>
     </div>

     <div class="block">
          <h4>Color:</h4>
           black,
           <span>and white</span>
     </div>

     <div class="block">
           <h4>Date:</h4> 2020
     </div>
              
     <div class="block">
          <h4>Time:</h4>
          <time datetime="12">12 clock</time>
     </div>
</div>

我的PHP:

$html = file_get_html("$url");

foreach ($html->find('#article') as $ret) {
    foreach ($ret->find('.block') as $pa) {
        foreach ($pa->find('h4') as $e) {
            if (strpos($e->innerhtml, "Price:") !== FALSE) {
                $str = $e->innerhtml;
                $price = $str->parent()->innertext;
                //$price = $str->plaintext;
                echo $price;
            }
        }
    }
}

我想检查 <h4>Price:<h4> 是否存在然后显示 .block 内容而不是包含 h4。
但我一无所获。
对不起我的英语

您可以使用如下函数。它在具有 article ID 的元素中查找具有 block class 的元素中的任何 <h4>,然后检查其文本。如果匹配,它会删除标题和 returns 块中剩余内容的文本:

function findValue($html, string $key): ?string
{
    foreach ($html->find('#article .block h4') as $h4) {
        if ($h4->innertext() === "{$key}:") {
            $h4 = clone $h4;  // to prevent altering the document
            $block = $h4->parent();
            $block->removeChild($h4);

            return $block->text();
        }
    }

    return null;
}

用法:

echo findValue($html, 'First name and last name'), PHP_EOL;  // name name
echo findValue($html, 'Price'), PHP_EOL;                     // ,163 (50% off)
echo findValue($html, 'Color'), PHP_EOL;                     // black, and white
echo findValue($html, 'Date'), PHP_EOL;                      // 2020
echo findValue($html, 'Time'), PHP_EOL;                      // 12 clock