title: Match the body of a function using Regex
body: <p>Given a dummy function as such:</p>
  
  <pre><code>public function handle()
  {
    if (isset($input['data']) {
      switch($data) {
        ...
      }
    } else {
      switch($data) {
        ...
      }
    }
  }
  </code></pre>
  
  <p>My intention is to get the contents of that function, the problem is matching nested patterns of curly braces <code>{...}</code>.</p>
  
  <p>I've come across <a href="http://php.net/manual/en/regexp.reference.recursive.php" rel="nofollow">recursive patterns</a> but couldn't get my head around a regex that would match the function's body.</p>
  
  <p>I've tried the following (no recursion):</p>
  
  <pre><code>$pattern = "/function\shandle\([a-zA-Z0-9_\$\s,]+\)?". // match "function handle(...)"
              '[\n\s]?[\t\s]*'. // regardless of the indentation preceding the {
              '{([^{}]*)}/'; // find everything within braces.
  
  preg_match($pattern, $contents, $match);
  </code></pre>
  
  <p>That pattern doesn't match at all. I am sure it is the last bit that is wrong <code>'{([^{}]*)}/'</code> since that pattern works when there are no other braces within the body.</p>
  
  <p>By replacing it with:</p>
  
  <pre><code>'{([^}]*)}/';
  </code></pre>
  
  <p>It matched till the closing <code>}</code> of the switch inside the <code>if</code> statement and stopped there (including <code>}</code> of the switch but excluding that of the <code>if</code>).</p>
  
  <p>As well as this pattern, same result:</p>
  
  <pre><code>'{(\K[^}]*(?=)})/m';
  </code></pre>