PHP xpath contains class and does not contain class
Asked Answered
G

3

28

The title sums it up. I'm trying to query an HTML file for all div tags that contain the class result and does not contain the class grid.

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

Thanks!

Gitt answered 14/1, 2013 at 18:16 Comment(1)
I haven't tried very much, only //div[contains(@class, 'result') and not contains(@class, 'grid')] and //div[contains(@class, 'result')][not contains(@class, 'grid')] but it was very apparent that my syntax was off right at the get goGitt
S
50

This should do it:

<?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";
}
Shiller answered 14/1, 2013 at 18:28 Comment(3)
This would also match anything with class = "*result" i.e. "someResult". So you gotta concat spaces to it.Renewal
thanks for the comment crush, that is extremely helpful. as for the solution I'm certain this will work so I'll be giving credit once I'm at a computer and have verified the code. one last question: as a relatively new programmer, where should I be going for my solutions? I feel that asking questions on SO is lazy and that google provides messy resources. any advice? thanks again guysGitt
Following @Renewal 's comment, I think the correct way is //div[contains(concat(' ', normalize-space(@class), ' '), ' result ')], or //div[@class and contains(concat(' ', normalize-space(@class), ' '), ' result ')].Hillinck
R
13

Your XPath would be //div[contains(concat(' ', @class, ' '), ' result ') and not(contains(concat(' ', @class, ' '), ' grid '))]

Renewal answered 14/1, 2013 at 18:26 Comment(0)
F
8

The XPATH syntax would be...

//div[not(contains(@class, 'grid'))]
Farrison answered 14/1, 2013 at 18:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.