title: PHP: How do I remove nested tags, and relocate them in an un-nested way?
body: <p>I need to remove all occurrences of a bb style tag from a string.  The tags can be nested, and this is where I am failing.  I also need to relocate each tag and contents to the end of the string, and replace the tag with an HTML element.  I have tried to play with regex and preg_replace_callback, but I have only been so far unsuccessful. I also tried to modify the following, and have also had no luck:
  <a href="https://stackoverflow.com/questions/3581870/removing-nested-bbcode-quotes-in-php">Removing nested bbcode (quotes) in PHP</a>
  and
  <a href="https://stackoverflow.com/questions/1114916/how-can-i-remove-an-html-element-and-its-contents-using-regex">How can I remove an html element and it&#39;s contents using RegEx</a> I don't think I can use an HTML parser <a href="http://simplehtmldom.sourceforge.net/" rel="nofollow noreferrer">like this</a> because the HTML is malformed (children in elements that can't have children).</p>
  
  <p>Here is what the string looks like:</p>
  
  <pre><code>This is some 
  [tag] attribute=1 attribute2=1 
       [tag] attribute=1 attribute2=1 [/tag] 
       [tag] attribute=1 attribute2=1 [/tag]
  [/tag]
   text.
  </code></pre>
  
  <p>The result should look like this:</p>
  
  <pre><code>This is some text.
  &lt;br attribute=1 attribute2=1&gt;
  &lt;br attribute=1 attribute2=1&gt;
  &lt;br attribute=1 attribute2=1&gt;
  </code></pre>
  
  <p>Any help would be appreciated.</p>