PHP xpath包含类,不包含类

Rob*_*Rob 21 php xpath domxpath xpathquery

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

<div class="result grid">skip this div</div>
<div class="result">grab this one</div>
Run Code Online (Sandbox Code Playgroud)

谢谢!

Sea*_*ght 39

这应该这样做:

<?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";
}
Run Code Online (Sandbox Code Playgroud)

  • 这也将与class =“ * result”即“ someResult”的任何内容匹配。因此,您必须为其添加空间。 (2认同)

cru*_*ush 11

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


wlv*_*vrn 7

XPATH语法将是......

//div[not(contains(@class, 'grid'))]
Run Code Online (Sandbox Code Playgroud)