How to match a regex only if it's not inside of a tag
<p>I'm trying to match <code>'&lt;TAG2&gt;'</code> only if it's not inside of <code>&lt;TAG&gt;</code>.</p>

<p>For example:</p>

<pre><code>This is a WORD --- Match
&lt;TAG&gt;&lt;TAG2&gt;xxx&lt;/TAG2&gt;&lt;/TAG&gt; --- Not a match
&lt;TAG&gt;xxxxxxx&lt;TAG2&gt;yyyy&lt;/TAG2&gt;xxxxxxx&lt;/TAG&gt;  --- Not a match
</code></pre>

<p>I'm using PHP so I can't do a variable length negative look-behind.</p>

<p>I tried using the regex in <a href="https://stackoverflow.com/questions/24356167/match-text-not-inside-span-tags">Match text not inside span tags</a>, but this doesn't work in my case if there's multiple tags.</p>

<pre><code>&lt;TAG&gt;&lt;TAG2&gt;xxx&lt;/TAG2&gt;&lt;/TAG&gt;
&lt;TAG&gt;&lt;TAG2&gt;xxx&lt;/TAG2&gt;&lt;/TAG&gt;  - This will match from the first &lt;TAG2&gt; to  the end of the second &lt;/TAG2&gt;.  I'm assuming this is because my regex includes &lt;TAG2&gt;[\s\S]*&lt;/TAG2&gt;
</code></pre>