title: PHP preg_match group repetition
body: <p>I have a (php5.2 and 5.3) regex that needs to extract the first $x sentences from a user post (which may include email addresses and hyperlinks) and am having trouble trying to find out why (and yes, it's an ugly regex; I'll optimise it when it works):</p>
  
  <pre><code>/^(([^.!?]+|(\w+[.@?&amp;=%:])+\w+)+[.!?]+\s){0,4}/
  </code></pre>
  
  <p>returns the first four sentences, but </p>
  
  <pre><code>/^(([^.!?]+|(\w+[.@?&amp;=%:])+\w+)+[.!?]+\s){0,5}/
  </code></pre>
  
  <p>returns no matches.  It's my understanding that {0,5} should match the previous group between 0 and 5 times, and as such should still work if it can only match it 4 times.</p>
  
  <p>Can anyone shed some light on this behaviour?</p>
  
  <p>Update: $x is just an arbitrary number; using {0,$x} in the regex.  Post is filtered to be sentences separated by a single space. Sorry for the ugly expression... been looking into this for a couple of days now, and it's doing my head in... Made the changes suggested by sawa.  My main question is about the behaviour, and the content that the group matches shouldn't matter that much.</p>
  
  <p>Update2: This is essentially what I'm doing:</p>
  
  <pre><code>function extractSummary($message, $limit) {
    $expr = '/^(([^.!?]+|(\w+[.@?&amp;=%:])+\w+)+[.!?]+\s){0,'.$limit.'}/';
    $msg = preg_replace('/[\x00-\x1f\x80-\xff]/', "\n" strip_tags($message));
    $msg = trim(preg_replace('/(\n|\s|&amp;nbsp;)+/', ' ', $msg)).' ';
    preg_match($expr, $msg, $summary);
    return $summary[0];
  }
  </code></pre>
  
  <p>A sentence (in my mind at least, without going into NLP territory, cos its just for one function in the site) is anything up to a period, exclamation point or question mark, but periods can appear within the sentence in an email address of URL.  The last version of this regex just counted up to 5 periods, and thus broke on links and email addresses.</p>
  
  <p>Update 3: Reallising that I've just added even more horrible code, I'll explain the last.  Some posted content was found to have non-printing chars (like \r, etc) that didn't play nicely with the regex, so I remove non-printing chars with the first preg_replace.  The second replaces any further whitespace groups with a single space, so the sentences are hopefully separated by exactly one space.</p>