200 of 410 menu

The preg_match_all Function

The preg_match_all function performs a global search for a pattern in a string. The first parameter is the regular expression, the second is the string to search, the third is the array to store the results. The fourth optional parameter defines the type of the returned structure, and the fifth optional parameter is the offset of the start of the search.

Syntax

preg_match_all(pattern, subject, matches, [flags], [offset]);

Flags

Let's see what values the fourth parameter can take:

Parameter Description
PREG_PATTERN_ORDER Default mode. Results are grouped by capturing groups - the zero element of the array contains the zero groups, the first element of the array contains the first groups and so on.
PREG_SET_ORDER Results are grouped by matches - each element of the array contains an array with the found capturing groups.
PREG_OFFSET_CAPTURE For each match, its position in the string is returned. Each result is an array where the zero element contains the match, and the first one - its offset.
PREG_UNMATCHED_AS_NULL Unmatched groups are returned as null instead of empty strings.

Example

Let's find all digits in the string:

<?php $str = 'abc 123 def 456'; preg_match_all('/\d+/', $str, $res); var_dump($res[0]); ?>

Code execution result:

['123', '456']

Example

Let's find all letters 'a' in the string:

<?php $str = 'banana'; preg_match_all('/a/', $str, $res); var_dump($res[0]); ?>

Code execution result:

['a', 'a', 'a']

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); var_dump($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); var_dump($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' ]

See Also

  • the preg_match function,
    which finds the first match of a regular expression
  • the preg_replace function,
    which performs search and replace by regular expression
byenru