php - 使用preg_match找到的字符串的parentNode

时间:2012-06-17 22:32:48

标签: php preg-match domdocument parent-node

我正在尝试访问使用preg_match找到的元素的parentNode,因为我想通过文档的DOM读取通过regex找到的结果。我无法通过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>

1 个答案:

答案 0 :(得分:1)

使用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;