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

php-使用xpath排除包含两个特定单词中的任何一个的内部类

(php - Using xpath to exclude inner classes that contains any of 2 certain words)

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

我正在使用以下代码返回div类名及其内部Li类名的数组。它的效果很好,但我想排除包含两个特定单词(愿望清单和/或比较)中任何一个的Li类。我尝试了“不包含”的组合,但是语法不正确。

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

例如,如果在以下示例中我想排除包含文本“ wishlist”或“ compare”的Li类,则我不希望返回“ top-menu-item-6”和“ top-menu-item-7”在数组中。

        <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>

如果包含“ wishlist”和/或“ compare”,则以下行需要正确的语法以不包括在内,但我无法获得它:

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

如果有人可以帮助你,谢谢。

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

除了如何处理它们之外,如果我对你的理解正确,那么这应该从问题中的html中提取目标属性值:

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);

}

输出:

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