For example I have the text
a1aabca2aa3adefa4a
I want to extract 2 and 3 with a regex between abc and def, so 1 and 4 should be not included in the result.
I tried this
if(preg_match_all('#abc(?:a(\d)a)+def#is', file_get_contents('test.txt'), $m, PREG_SET_ORDER))
print_r($m);
I get this
> Array
(
[0] => Array
(
[0] => abca1aa2adef
[1] => 3
)
)
But I want this
Array
(
[0] => Array
(
[0] => abca1aa2adef
[1] => 2
[2] => 3
)
)
Is this possible with one preg_match_all call? How can I do it?
Thanks
works on your example. It assumes that there is exactly one instance of
abcanddefper line in your string.The reason why your attempt didn’t work is that your capturing group
(\d)that matches the digit is within another, repeated group(?:a(\d)a)+. With every repetition, the result of the capture is overwritten. This is how regular expressions work.In other words – see what’s happening during the match: