Posted By

pvq on 09/06/14


Tagged

recursive regexp nested


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

pvq
JeffSFO


Search nested html elements


 / Published in: PHP
 

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.

  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  

You need to login to post a comment.