title: Regular expression for nested tags (innermost to make it easier)
body: <p>I researched this quite a bit, but couldn't find a working example how to match nested html tags <strong>with</strong> attributes. I know it is possible to match balanced/nested innermost tags without attributes (for example a regex for  and  would be  <code>#&lt;div\b[^&gt;]*&gt;(?:(?&gt; [^&lt;]+ )  |&lt;(?!div\b[^&gt;]*&gt;))*?&lt;/div&gt;</code>#x).</p>
  
  <p>However, I would like to see a regex pattern that finds an html tag pair with attributes.</p>
  
  <p>Example: It basically should match</p>
  
  <pre><code>&lt;div class="aaa"&gt; **&lt;div class="aaa"&gt;** &lt;div&gt; &lt;div&gt; &lt;/div&gt; **&lt;/div&gt;** &lt;/div&gt;
  </code></pre>
  
  <p>and not</p>
  
  <pre><code>&lt;div class="aaa"&gt; **&lt;div class="aaa"&gt;** &lt;div&gt; &lt;div&gt; **&lt;/div&gt;** &lt;/div&gt; &lt;/div&gt;
  </code></pre>
  
  <p>Anybody has some ideas?</p>
  
  <p>For testing purposes we could use: <a href="http://www.lumadis.be/regex/test_regex.php" rel="nofollow noreferrer">http://www.lumadis.be/regex/test_regex.php</a></p>
  
  <hr>
  
  <p>PS. Steven mentioned a solution in his blog (actually in a comment), but it doesn't work</p>
  
  <p><a href="http://blog.stevenlevithan.com/archives/match-innermost-html-element" rel="nofollow noreferrer">http://blog.stevenlevithan.com/archives/match-innermost-html-element</a></p>
  
  <pre><code>$regex = '/&lt;div\b[^&gt;]+?\bid\s*=\s*"MyID"[^&gt;]*&gt;(?:((?:[^&lt;]++|&lt;(?!\/?div\b[^&gt;]*&gt;))+)|(&lt;div\b[^&gt;]*&gt;(?&gt;(?1)|(?2))*&lt;\/div&gt;))?&lt;\/div&gt;/i';
  </code></pre>