title: PHP preg-match-all regex
body: <p>I would like to capture each of these in their own group with preg_match_all in PHP.</p>
  
  <ol>
  <li>The chapter, section, or page</li>
  <li>The number (or letter if it has one) of the specified chapter, section, or page. If there is a single space between them it should be taken into account</li>
  <li>The words "and", "or"</li>
  </ol>
  
  <p>Keeping in mind that the number of items in the string may be dynamic, the regex should work on all the examples below:</p>
  
  <ol>
  <li>Ch1 and Sect2b</li>
  <li>Ch 4 x blahunwantedtext and Sect 5y and Sect6 z and Ch7 or Ch8</li>
  </ol>
  
  <p>This is what I managed to come up with so far:</p>
  
  <pre><code>&lt;?php
  
      $str = 'Ch 1 a and Sect 2b and Pg3';
      preg_match_all ('/([a-z]+)([\s]?[0-9]+)([\s]?[a-z]*)([\s]?and*[\s]?)/is', $str, $matches);
  
      Array
      (
          [0] =&gt; Array
              (
                  [0] =&gt; Ch 1 a and 
                  [1] =&gt; Sect 2b and 
              )
  
          [1] =&gt; Array
              (
                  [0] =&gt; Ch
                  [1] =&gt; Sect
              )
  
          [2] =&gt; Array
              (
                  [0] =&gt;  1
                  [1] =&gt;  2
              )
  
          [3] =&gt; Array
              (
                  [0] =&gt;  a
                  [1] =&gt; b
              )
  
          [4] =&gt; Array
              (
                  [0] =&gt;  and 
                  [1] =&gt;  and 
              )
  
      )
  </code></pre>
  
  <p>I'm unable to match the last portions of the string (Pg3) in my array.</p>
  
  <p>The expected result should be:</p>
  
  <pre><code>    Array
      (
          [0] =&gt; Array
              (
                  [0] =&gt; Ch 1 a and 
                  [1] =&gt; Sect 2b and 
                  [2] =&gt; Pg3
              )
  
          [1] =&gt; Array
              (
                  [0] =&gt; Ch
                  [1] =&gt; Sect
                  [2] =&gt; Pg
              )
  
          [2] =&gt; Array
              (
                  [0] =&gt;  1
                  [1] =&gt;  2
                  [2] =&gt;  3
              )
  
          [3] =&gt; Array
              (
                  [0] =&gt;  a
                  [1] =&gt; b
                  [2] =&gt; 
              )
  
          [4] =&gt; Array
              (
                  [0] =&gt;  and 
                  [1] =&gt;  and 
                  [2] =&gt;  
              )
  
      )
  </code></pre>