More information about the Underscore mailing list

[_] php regex - remove nested lists in nav

Martin Wheatley martin at spodnet.net
Fri Feb 1 11:04:39 GMT 2013

On 01/02/2013 10:38 AM, juan kennaugh wrote:
> Hi all
>
> I'm no regex or php expert - so wondering if anyone could tell me if
> there's a simple way of removing a nested list from a nav markup string
> using regex?
>
> Cheers
>
> Juan
>


$doc = new DOMDocument();
$doc->loadHTML($string);

$xpath = new DOMXPath($doc);

foreach ($xpath->query('/html/body/ul/li/ul') as $node) {
	$node->parentNode->removeChild($node);
}

$string = preg_replace(array("/^\<\!DOCTYPE.*?<html><body>/si", 
"!</body></html>$!si"), "", $doc->saveHTML());

(The last line strips off body etc that DOMDocumentadds, personally I 
use SmartDOMDocument which is just a wrapper, to handle this rather than 
DOMDocumen).

Martin