Return to Snippet

Revision: 67303
at September 6, 2014 00:03 by pvq


Initial Code
// dummy html
$html = '<div id="a1"><div id="a1-1"></div><div id="a1-2"></div></div><div id="a2"></div>';

// the magic
preg_match_all('/<([a-z]+)[^>]*>(?:(?:(?!<\1[^>]*>|<\/\1>).|(?R))*)<\/\1>/si', $html, $matches);

// print result
printf('<pre>%s</pre>', str_replace('<', '&lt;', print_r($matches, true)));

Initial URL


Initial Description
Match nested html elements using regular expressions.

Replace the first part of the magic "[a-z]+" to search for a specific tag, e.g. "div".

Loop the magic on matched parts to create a recursive match.

Initial Title
Search nested html elements

Initial Tags
regexp

Initial Language
PHP