title: Extract code from nested curly braces, including multiple internal curly braces in PHP
body: <p>So, I got some ideas off here about how to do this and took on board some of the code suggestions; I have LaTeX files with components in the form 
  <code>{upper}{lower}</code> where <code>upper</code> could be anything from plain text to LaTeX including its own nested {} and <code>lower</code> could be blank or substantial latex. Desired output is a pair of PHP strings <code>$upper</code> and <code>$lower</code> that contain only the content of the two parent braces.</p>
  
  <pre><code>$upperlowerQ='some string';  // in format {upper}{lower}
  $qparts=nestor($upperlowerQ);
  $upper=$qparts[0];
  $lower=$qparts[1];
  
  
  function nestor($subject) {
      $result = false;    
      preg_match_all('~[^{}]+|\{(?&lt;nested&gt;(?R)*)\}~', $subject, $matches);
  
      foreach($matches['nested'] as $match) {
          if ($match != "") {
              $result[] = $match;
              $nesty = nestor($match);
              if ($nesty) 
                  $result = array_merge($result,$nesty); 
          }
      }
      return $result;
  }
  </code></pre>
  
  <p>This function works for about 95% of my data (this upper/lower splitting is called in a loop for about 1,000 times) but it is failing on a few. An example of something it fails on looks like this:</p>
  
  <pre><code>{Draw an example of a reciprocal graph in the form $y=\frac{a}{x}$}{
  \begin{tikzpicture}
      \begin{axis}[xmin=-8,xmax=8,ymin=-5,ymax=12,samples=50,grid=both,grid style={gray!30},xtick={-8,...,8},ytick={-5,...,12},axis x line = bottom,
          axis y line = left, axis lines=middle]
      \end{axis}
  \end{tikzpicture}\par
  %ans: smooth reciprocal function plotted.
  }
  </code></pre>
  
  <p>which gives:
  <code>$upper</code> as <code>Draw an example of a reciprocal graph in the form $y=\frac{a}{x}$</code> (which is correct) but <code>$lower</code> as <code>a</code>, which is the numerator of the fraction in the upper part... any ideas appreciated. It is always <code>$lower</code> that is wrong... <code>$upper</code> seems correct.</p>