Search nested html elements


/ Published in: PHP
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. // dummy html
  2. $html = '<div id="a1"><div id="a1-1"></div><div id="a1-2"></div></div><div id="a2"></div>';
  3.  
  4. // the magic
  5. preg_match_all('/<([a-z]+)[^>]*>(?:(?:(?!<\1[^>]*>|<\/\1>).|(?R))*)<\/\1>/si', $html, $matches);
  6.  
  7. // print result
  8. printf('<pre>%s</pre>', str_replace('<', '&lt;', print_r($matches, true)));

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.