⊗ppPmRgSBh 251 of 447 menu

Changing preg_match_all Behavior in PHP

Using the fourth parameter of the preg_match_all function, you can change the way capture groups are grouped.

Let's see what values this parameter can take:

Parameter Description
PREG_PATTERN_ORDER Default mode. Results are grouped by capture groups - the zero element of the array contains the zero capture groups, the first element of the array contains the first capture groups and so on.
PREG_SET_ORDER Results are grouped by matches - each element of the array contains an array with the found capture groups.

Now let's look at the usage of this parameter with examples:

Example

Let's extract all timestamps from the string and their components:

<?php $time = '12:01:02 13:03:04 14:05:06'; preg_match_all('#(\d\d):(\d\d):(\d\d)#', $time, $res); print_r($res); ?>

Code execution result:

[ 0 => ['12:01:02', '13:03:04', '14:05:06'], 1 => ['12', '13', '14'], 2 => ['01', '03', '05'], 3 => ['02', '04', '06'] ]

Example

Now let's use the PREG_SET_ORDER flag for grouping by matches:

<?php $time = '12:01:02 13:03:04 14:05:06'; preg_match_all('#(\d\d):(\d\d):(\d\d)#', $time, $res, PREG_SET_ORDER); print_r($res); ?>

Code execution result:

[ 0 => '12:01:02', 1 => '12', 2 => '01', 3 => '02' ], [ 0 => '13:03:04', 1 => '13', 2 => '03', 3 => '04' ], [ 0 => '14:05:06', 1 => '14', 2 => '05', 3 => '06' ]

Practical Tasks

Given a string with dates:

<?php $str = '2023-10-29 2024-11-30 2025-12-31'; ?>

Find all dates, separating the year, month, and day into separate capture groups. Make it so that the first subarray contains the first date with its capture groups, the second subarray - the second with its capture groups, and so on.

byenru