简体   繁体   中英

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?

$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 . 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. So you are returning the parent node of any match; ie: the parent <li> of any match, in your example.

Finally, we iterate over all matching <li> elements and remove each one from its parent node.

Here's more information on 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; 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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