PHP xpath 包含类,不包含类

2022-08-30 16:25:46

标题总结了这一点。我正在尝试查询HTML文件,以获取包含该类且不包含该类的所有div标签。resultgrid

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

谢谢!


答案 1

这应该这样做:

<?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";
}

答案 2

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


推荐