I want to match all 1 digit and 2 digit numbers using regex.
Subject string: '12345'
Expected match: 1,2,3,4,5,12,23,34,45
I’m trying: d(d)?
but as result i get 12,2,34,3,5
Advertisement
Answer
You can use
$s = "12345"; $res = []; if (preg_match_all('~(?=((d)d?))~', $s, $m, PREG_SET_ORDER)) { $single = []; $double = []; foreach ($m as $v) { if ($v[1] != $v[2]) { array_push($single, $v[2]); array_push($double, $v[1]); } else { array_push($single, $v[1]); } } $res = array_merge($single, $double); print_r( $res ); }
See the PHP demo. Output:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 12 [6] => 23 [7] => 34 [8] => 45 )
NOTES:
(?=((d)d?))
– a regex that captures into Group 1 two or one digits, and into Group 2 the first digit of the previous sequencePREG_SET_ORDER
groups the captures into the same parts of the match array- If the match is a single digit, the
$double
array is not modified - The final array is a combination of single digit array + double digit array.