使用preg_match查找特定的HTML标记组合


Find specific HTML tag combination with preg_match

我正在尝试创建一个preg_match,它可以在HTML文档中查找一系列标记。

示例HTML:

<div class="importantclass">
  <p>some thing</p>
  <p>some more things</p>
</div>
<div class="importantclass">
  <b>some text</b>
  <p>NEEDLE</p>
</div>

我需要找到带有div class="importantclass"的标签的组合,以及后面带有特定NEEDLE Text的p-tag。

然后我需要返回打开div类的位置。注意:我不想得到匹配,因为important类div.是第一次出现

是否有可能在不使用DOM和只使用regexp的情况下完成此操作

谢谢你的提示!

这对你有用吗?

<?php
    $html = <<< LOB
<div class="importantclass">
  <p>some thing</p>
  <p>some more things</p>
</div>
<div class="importantclass">
  <b>some text</b>
  <p>FIND ME</p>
</div>
LOB;
    $needle = "FIND ME";
    preg_match_all('%(<div.*?class="importantclass">.*?</div>)%sim', $html, $matches, PREG_PATTERN_ORDER);
    for ($i = 0; $i < count($matches[1]); $i++) {
        if (preg_match("%<p>$needle</p>%im", $matches[1][$i])) {
            echo "MATCH FOUND!<br>";
            echo "POSITION $i<br>";
            echo htmlentities( $matches[1][$i]);
        }
}

DEMO