You can use preg_match_all()and discard matches that you are not interested in, or use a loop with preg_match(). The second option would be better if you were worried about the cost of scanning a large string.
This example is limited to two matches when there are actually 3 in the entire row:
<?php
$str = "ab1ab2ab3ab4c";
for ($offset = 0, $n = 0;
$n < 2 && preg_match('/b([0-9])/', $str, $matches, PREG_OFFSET_CAPTURE, $offset);
++$n, $offset = $matches[0][1] + 1) {
var_dump($matches);
}
Indeed, the loop would whileprobably be clearer than the forreflection loop ;)
source
share