Non-Capturing Parentheses in PHP Regex
Parentheses ()
perform two functions -
grouping characters and the capturing function.
But what to do if we need to group,
but not capture?
To solve this problem, special
non-capturing parentheses (?: )
were invented - they group, but do not capture.
Example
In the following example, the first parentheses are needed for grouping, and the second - for capturing. However, both parentheses save data into the capture group:
<?php
$str = 'abab123';
$reg = '#(ab)+([1-9]+)#';
preg_match_all($reg, $str, $res);
?>
As a result, our capture groups will contain the following:
<?php
var_dump($res[0]); // will output 'abab123'
var_dump($res[1]); // will output 'ab'
var_dump($res[2]); // will output '123'
?>
Example
Let's make it so that the first pair of parentheses only groups, but does not capture:
<?php
$str = 'abab123';
$reg = '#(?:ab)+([1-9]+)#';
preg_match_all($reg, $str, $res);
?>
As a result, the first capture group will contain our number:
<?php
var_dump($res[1]); // will output '123'
?>
Practice Tasks
Given substrings separated into two parts
by an arbitrary number of $@
pairs:
<?php
$str = 'aaa$@bbb aaa$@$@bbb aaa$@$@$@bbb';
?>
Find each of these substrings and for each found substring, put into the first capture group what comes before the separator, and into the second capture group - what comes after the separator.