title: PCRE: Lazy and Greedy at the same time (Possessive Quantifiers)
body: <p>I am trying to match a series of text strings with PCRE on PHP, and am having trouble getting all the matches in between the first and second.</p>
  
  <p>If anyone wonders why on Earth I would want to do this, it's because of Doc Comments. Oh, how I wish Zend would make native/plugin functions to read Doc Comments from a PHP file...</p>
  
  <p>The following example (plain) text will be used for the problem. It will always be pure PHP  code, with only one opening tag at the beginning of the file, no closing. You can assume that the syntax will always be correct.</p>
  
  <pre><code>&lt;?php
    class someClass extends someExample
    {
      function doSomething($someArg = 'someValue')
      {
        // Nested code blocks...
        if($boolTest){}
      }
      private function killFurbies(){}
      protected function runSomething(){}
    }
  
    abstract
    class anotherClass
    {
      public function __construct(){}
      abstract function saveTheWhales();
    }
  
    function globalFunc(){}
  </code></pre>
  
  <h2>Problem</h2>
  
  <p>Trying to match all methods in a class; my RegEx does not find the method <code>killFurbies()</code> at all. Letting it be greedy means it only matches the last method in a class, and letting it be lazy means it only matches the first method.</p>
  
  <pre><code>$part = '.*';  // Greedy
  $part = '.*?'; // Lazy
  
  $regex = '%class(?:\\n|\\r|\\s)+([a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*)'
         . '.*?\{' . $part .'(?:(public|protected|private)(?:\\n|\\r|\\s)+)?'
         . 'function(?:\\n|\\r|\\s)+([a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff'
         . ']*)(?:\\n|\\r|\\s)*\\(%ms';
  
  preg_match_all($regex, file_get_contents(__EXAMPLE__), $matches, PREG_SET_ORDER);
  var_dump($matches);
  </code></pre>
  
  <p>Results in:</p>
  
  <pre><code>// Lazy:
  array(2) {
    [0]=&gt;
    array(4) {
      [0]=&gt;
      // Omitted.
      [1]=&gt;
      string(9) "someClass"
      [2]=&gt;
      string(0) ""
      [3]=&gt;
      string(11) "doSomething"
    }
    [1]=&gt;
    array(4) {
      [0]=&gt;
      // Omitted.
      [1]=&gt;
      string(12) "anotherClass"
      [2]=&gt;
      string(6) "public"
      [3]=&gt;
      string(11) "__construct"
    }
  }
  
  // Greedy:
  array(2) {
    [0]=&gt;
    array(4) {
      [0]=&gt;
      // Omitted.
      [1]=&gt;
      string(9) "someClass"
      [2]=&gt;
      string(0) ""
      [3]=&gt;
      string(13) "saveTheWhales"
    }
    [1]=&gt;
    array(4) {
      [0]=&gt;
      // Omitted.
      [1]=&gt;
      string(12) "anotherClass"
      [2]=&gt;
      string(0) ""
      [3]=&gt;
      string(13) "saveTheWhales"
    }
  }
  </code></pre>
  
  <p>How do I match all? :S</p>
  
  <p>Any help would be gratefully appreciated, as I already feel this question is ridiculous as I'm typing it out. Anyone attempting to answer a question like this is braver than me!</p>