Warm tip: This article is reproduced from serverfault.com, please click

Using xpath to exclude inner classes that contains any of 2 certain words

发布于 2020-12-01 01:29:31

I am using the following to return an array of div class names and their inner Li class names. It works great, but I would like to exclude Li classes that contain any of 2 certain words (wishlist and/or compare). I have tried combinations of "not contains" but can't get the syntax right.

function GetInnerDivClasses(){
$dom = new DOMDocument();
@$dom->loadHTML(SourceHtml());
$xpath = new DOMXpath($dom);

$classNames = [];
foreach ($xpath->query(".//div[contains(@class, ' top-menu-')]") as $div) {
foreach ($xpath->query('.//li/@class', $div) as $li) {
$classNames[$div->getAttribute('class')][] = $li->textContent;
}
}
return $classNames;
}

For example if I wanted to exclude Li Classes that contain the text "wishlist" or "compare" in the following example, then I would not like "top-menu-item-6" and "top-menu-item-7"returned in the array.

        <div class="top-menu top-menu-2">
       <ul class="j-menu">
              <li class="menu-item top-menu-item top-menu-item-1">
              <a href="https://www.example.com/index.php?route=information/contact" ><span class="links-text">Contact</span></a>
        </li>

              <li class="top-menu-item-2">
              <a href="https://www.example.com/index.php?route=information/information&amp;information_id=7" ><span class="links-text">FAQ</span></a>
        </li>

              <li class="top-menu-item-6">
              <a href="https://www.example.com/index.php?route=account/wishlist" ><span class="links-text">Wishlist</span><span class="count-badge wishlist-badge">1</span></a>
        </li>

              <li class="top-menu-item-7">
              <a href="https://www.example.com/index.php?route=product/compare" ><span class="links-text">Compare</span><span class="count-badge compare-badge count-zero">0</span></a>
        </li>

      </ul>

The following line needs the correct syntax to not include if contains either "wishlist" and/or "compare", but I can't get it:

foreach ($xpath->query('.//li/@class', $div) as $li) {

If someone could please help Thanks.

Questioner
TonyC
Viewed
0
Jack Fleeting 2020-12-01 10:55:43

Aside from what to do with them, if I understand you correctly, this should extract your target attribute values from the html in the question:

echo $xpath->query('.//div/@class')[0]->textContent . PHP_EOL;

foreach ($xpath->query('//li[a[not(span[(contains(@class,"compare"))])][not(span[(contains(@class,"wishlist"))])]]/@class') as $target) {
echo($target->textContent . PHP_EOL);

}

Output:

top-menu top-menu-2
menu-item top-menu-item top-menu-item-1
top-menu-item-2