与 preg_match 一起找到的字符串的父节点


parentNode of a string found with preg_match

我正在尝试访问用preg_match找到的元素的 parentNode,因为我想通过文档的 DOM 读取用正则表达式找到的结果。我无法通过 PHP 的 DOMDocument 直接访问它,因为div 的数量是可变的,它们没有实际 ID 或任何其他能够匹配的属性。

为了说明这一点:在下面的示例中,我将match_me与preg_match匹配,然后我想访问 parentNode (div) 并将所有子元素(p )放在 DOMdocument 对象中,以便我可以轻松显示它们。

   <div> 
   .... variable amount of divs
   <div>
   <div>
       <p>1 match_me</p><p>2</p>
   </div>
   </div>
   </div>

使用 DOMXpath 按节点子节点的值查询节点:

$dom = new DOMDocument();
// Load your doc however necessary...
$xpath = new DOMXpath($dom);
// This query should match the parent div itself
$nodes = $xpath->query('/div[p/text() = "1 match_me"]');
$your_div = $nodes->item(0);
// Do something with the children
$p_tags = $your_div->childNodes;

// Or in this version, the query returns the `<p>` on which `parentNode` is called
$ndoes = $xpath->query('/p[text() = "1 match_me"]');
$your_div = $nodes->item(0)->parentNode;