Thread: RegEx
View Single Post
Old 12-11-2007, 05:53 PM   #4 (permalink)
Salathe
Moderateur
RegEx Guru PHP Guru Top Contributor Advanced Programmer 
 
Salathe's Avatar
 
Join Date: Apr 2007
Posts: 1,381
Thanks: 5
Salathe is on a distinguished road
Default

Thanks Geert. The two items ?: and ? are not related. When you specify a group such as (abc), that group is returned as part of the matches array -- it captures whatever is inside as a special group. If you use (?:abc) then the group becomes non-capturing, which simply means that the group is not returned with the matches.

For those who like code snippets, here's what happens:
php Code:
preg_match('/t(es)t/', 'test', $matches);
/*
Array
(
    [0] => test
    [1] => es
)
*/


preg_match('/t(?:es)t/', 'test', $matches);
/*
Array
(
    [0] => test
)
*/

In extension to Geert's post above, the U (PCRE_UNGREEDY) modifier can be used at the end of the regex in order to reverse the normal behaviour. By default, patterns are greedy but with the U modifier they will become non-greedy. In this case, if the ? is used (eg. (.*?) it will make the preceeding quantifier greedy. That's probably confusing to deal with at the moment so I just mention it as an aside.
Salathe is offline  
Reply With Quote
The Following User Says Thank You to Salathe For This Useful Post:
Matt83 (12-11-2007)