PHP xpath包含类,不包含类

时间:2013-01-14 18:16:12

标签: php xpath domxpath xpathquery

标题总结了它。我正在尝试在HTML文件中查询包含类result并且不包含类grid的所有div标记。

<div class="result grid">skip this div</div>
<div class="result">grab this one</div>

谢谢!

3 个答案:

答案 0 :(得分:36)

这应该这样做:

<?php
$doc = new DOMDocument();
$doc->loadHTMLFile('test.html');

$xpath = new DOMXPath($doc);
$nodeList = $xpath->query(
    "//div[contains(@class, 'result') and not(contains(@class, 'grid'))]");

foreach ($nodeList as $node) {
  echo $node->nodeName . "\n";
}

答案 1 :(得分:10)

您的XPath将是//div[contains(concat(' ', @class, ' '), ' result ') and not(contains(concat(' ', @class, ' '), ' grid '))]

答案 2 :(得分:6)

XPATH语法是......

//div[not(contains(@class, 'grid'))]