How do I control whether parenthesis in my regular expression mark a sub group, do something else, or both?
For example if I have strings such as “AA12345” and “AB12345” and I want to preg_match for the first two letters which are always either AA or AB, I have:
preg_match('/(A(A|B)).*/',$string,$matches);
(I put the .* for the sake of this question because the rest of the string isn’t relevant)
With this setup, assuming $string=”AA12345″, I’m getting $matches =
Array
(
[0] => AA12345
[1] => AA
[2] => A
)
I don’t need or want the “[2] => A” as a result, but I can’t remove the parenthesis from the regex because they are needed for the OR operator. How do I deal with this? Just ignore the result, or is there a better way?
You can use a “non-capturing group” of the form
(?:...):As the documentation puts it: