简体   繁体   English

使用PHP按类名称删除列表项

[英]Remove list item by class name using PHP

I am trying to remove a parent list item when the child link has a class 'hide'. 我试图在子链接具有“隐藏”类时删除父列表项。 How would I get the class name and then remove the parent 'li' if a child within it has a the 'hide' class? 如果班级中的孩子有“隐藏”班级,我将如何获取班级名称,然后删除其父级“ li”?

$html = '<ul> 
    <li><a href="/first">First Item</a></li>
    <li><a class="hide" href="/first">First Item</a></li>
</ul>';

$dom = new DOMDocument;
@$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('li') as $tag){
    // Check if there is a hide and remove the parent list item
    }

You can use DOMXPath in conjunction with DOMDocument . 您可以将DOMXPathDOMDocument结合使用。 Try the following: 请尝试以下操作:

<?php

$html = '<ul>
    <li><a href="/first">First Item</a></li>
    <li><a class="hide" href="/first">Second Item</a></li>
</ul>';

$dom = new DOMDocument();
$dom->loadHTML($html);

$xpath = new DOMXPath($dom);
$elements = $xpath->query('//a[@class="hide"]/..');

foreach ($elements as $el) {
    $el->parentNode->removeChild($el);
}

echo $doc->saveHTML();

Yields: 产量:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd">

<html>
    <body>
        <ul>
            <li><a href="/first">First Item</a></li>
        </ul>
    </body>
</html>

The XPath expression //a[@class="hide"]/.. will match any <a> tags containing the "hide" class, and /.. returns its parent. XPath表达式//a[@class="hide"]/..将匹配任何包含“ hide”类的<a>标记,并且/..返回其父项。 So you are returning the parent node of any match; 因此,您将返回任何匹配项的父节点; ie: the parent <li> of any match, in your example. 即:在您的示例中,任何匹配项的父<li>

Finally, we iterate over all matching <li> elements and remove each one from its parent node. 最后,我们遍历所有匹配的<li>元素,并将每个元素从其父节点中删除。

Here's more information on DOMXPath::query() 以下是有关DOMXPath::query()的更多信息

Hope this helps :) 希望这可以帮助 :)

As i understand you need to delete the first li from the ul based on a class name of the internal a element; 据我了解,您需要根据内部a元素的类名从ul中删除第一个li; Here is a solution 这是一个解决方案

  $html = '<ul> 
        <li><a href="/first">First Item</a></li>
        <li><a class="hide" href="/first">First Item</a></li>
    </ul>';

    $doc = new DOMDocument;
    @$doc->loadHTML($html);
    $xpath = new DOMXpath($doc);

    $elements = $xpath->query("//ul/li/a[@class='hide']/parent::*/preceding-sibling::*[1]");


    foreach($elements as $node) {
      $node->parentNode->removeChild($node);
    };
    echo $doc->saveHTML();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM