Skip to content

Instantly share code, notes, and snippets.

@salathe
Created April 23, 2012 20:00
Show Gist options
  • Select an option

  • Save salathe/2473432 to your computer and use it in GitHub Desktop.

Select an option

Save salathe/2473432 to your computer and use it in GitHub Desktop.
AlVal
<?php
$ul = '<ul id="menu">
<li id="Thing 1" class="some_class">Thing 1</li>
<li id="Thing 2" class="someother_class">Thing 2</li>
<li id="Thing 3" class="some_class">Thing 3</li>
<li id="Thing 4" class="some_class">Thing 4</li>
</ul>';
$dom = new DOMDocument;
$dom->loadHTML($ul);
$xpath = new DOMXPath($dom);
// Finds all items that don't have class="some_class" *and* the
// items that have class="some_class" except for the first two of them.
$nodes = $xpath->query('//ul/li[@class != "some_class"] | (//ul/li[@class = "some_class"])[position() > 2]');
foreach ($nodes as $node) {
$node->parentNode->removeChild($node);
}
$menu = $xpath->query('//ul[@id="menu"]')->item(0);
echo $dom->saveXML($menu);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment