What is preg_match_all in php?

❮ PHP RegExp Reference

Example

Use a regular expression to do a case-insensitive search for "w3schools" in a string:

Try it Yourself »

Definition and Usage

The preg_match[] function returns whether a match was found in a string.

Syntax

preg_match[pattern, input, matches, flags, offset]

Parameter Values

ParameterDescription
pattern Required. Contains a regular expression indicating what to search for
input Required. The string in which the search will be performed
matches Optional. The variable used in this parameter will be populated with an array containing all of the matches that were found
flags Optional. A set of options that change how the matches array is structured:
  • PREG_OFFSET_CAPTURE - When this option is enabled, each match, instead of being a string, will be an array where the first element is a substring containing the match and the second element is the position of the first character of the substring in the input.
  • PREG_UNMATCHED_AS_NULL - When this option is enabled, unmatched subpatterns will be returned as NULL instead of as an empty string.
offset Optional. Defaults to 0. Indicates how far into the string to begin searching. The preg_match[] function will not find matches that occur before the position given in this parameter

Technical Details

Return Value:PHP Version:Changelog:
Returns 1 if a match was found, 0 if no matches were found and false if an error occurred
4+
PHP 7.2 - Added the PREG_UNMATCHED_AS_NULL flag

PHP 5.3.6 - The function returns false when the offset is longer than the length of the input

PHP 5.2.2 - Named subpatterns can use the [?'name'] and [? ] syntax in addition to the previous [?P]

More Examples

Example

Use PREG_OFFSET_CAPTURE to find the position in the input string in which the matches were found:

Try it Yourself »

❮ PHP RegExp Reference


[PHP 4, PHP 5, PHP 7, PHP 8]

preg_match_allPerform a global regular expression match

Description

preg_match_all[
    string $pattern,
    string $subject,
    array &$matches = null,
    int $flags = 0,
    int $offset = 0
]: int|false

After the first match is found, the subsequent searches are continued on from end of the last match.

Parameters

pattern

The pattern to search for, as a string.

subject

The input string.

matches

Array of all matches in multi-dimensional array ordered according to flags.

flags

Can be a combination of the following flags [note that it doesn't make sense to use PREG_PATTERN_ORDER together with PREG_SET_ORDER]:

PREG_PATTERN_ORDER

Orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on.

The above example will output:

example: , 
this is a test
example: , this is a test

So, $out[0] contains array of strings that matched full pattern, and $out[1] contains array of strings enclosed by tags.

If the pattern contains named subpatterns, $matches additionally contains entries for keys with the subpattern name.

If the pattern contains duplicate named subpatterns, only the rightmost subpattern is stored in $matches[NAME].

The above example will output:

Array
[
    [0] => 
    [1] => bar
]

PREG_SET_ORDER

Orders results so that $matches[0] is an array of first set of matches, $matches[1] is an array of second set of matches, and so on.

The above example will output:

example: , example:
this is a test
, this is a test

PREG_OFFSET_CAPTURE

If this flag is passed, for every occurring match the appendant string offset [in bytes] will also be returned. Note that this changes the value of matches into an array of arrays where every element is an array consisting of the matched string at offset 0 and its string offset into subject at offset 1.

The above example will output:

Array
[
    [0] => Array
        [
            [0] => Array
                [
                    [0] => foobarbaz
                    [1] => 0
                ]

        ]

    [1] => Array
        [
            [0] => Array
                [
                    [0] => foo
                    [1] => 0
                ]

        ]

    [2] => Array
        [
            [0] => Array
                [
                    [0] => bar
                    [1] => 3
                ]

        ]

    [3] => Array
        [
            [0] => Array
                [
                    [0] => baz
                    [1] => 6
                ]

        ]

]

PREG_UNMATCHED_AS_NULL

If this flag is passed, unmatched subpatterns are reported as null; otherwise they are reported as an empty string.

If no order flag is given, PREG_PATTERN_ORDER is assumed.

offset

Normally, the search starts from the beginning of the subject string. The optional parameter offset can be used to specify the alternate place from which to start the search [in bytes].

Note:

Using offset is not equivalent to passing substr[$subject, $offset] to preg_match_all[] in place of the subject string, because pattern can contain assertions such as ^, $ or [?

Example #2 Find matching HTML tags [greedy]

The above example will output:

matched: bold text
part 1: 
part 2: b
part 3: bold text
part 4: 

matched: click me
part 1: 
part 2: a
part 3: click me
part 4: 

Example #3 Using named subpattern

The above example will output:

Array
[
    [0] => Array
        [
            [0] => a: 1
            [1] => b: 2
            [2] => c: 3
        ]

    [name] => Array
        [
            [0] => a
            [1] => b
            [2] => c
        ]

    [1] => Array
        [
            [0] => a
            [1] => b
            [2] => c
        ]

    [digit] => Array
        [
            [0] => 1
            [1] => 2
            [2] => 3
        ]

    [2] => Array
        [
            [0] => 1
            [1] => 2
            [2] => 3
        ]

]

See Also

  • PCRE Patterns
  • preg_quote[] - Quote regular expression characters
  • preg_match[] - Perform a regular expression match
  • preg_replace[] - Perform a regular expression search and replace
  • preg_split[] - Split string by a regular expression
  • preg_last_error[] - Returns the error code of the last PCRE regex execution

buuh

11 years ago

if you want to extract all {token}s from a string:



output:

Array
[
    [0] => Array
        [
            [0] => {token1}
            [1] => {token2}
        ]

]

Daniel Klein

7 years ago

The code that john at mccarthy dot net posted is not necessary. If you want your results grouped by individual match simply use:

E.g.

mnc at u dot nu

16 years ago

PREG_OFFSET_CAPTURE always seems to provide byte offsets, rather than character position offsets, even when you are using the unicode /u modifier.

phpnet at sinful-music dot com

16 years ago

Here's some fleecy code to 1. validate RCF2822 conformity of address lists and 2. to extract the address specification [the part commonly known as 'email']. I wouldn't suggest using it for input form email checking, but it might be just what you want for other email applications. I know it can be optimized further, but that part I'll leave up to you nutcrackers. The total length of the resulting Regex is about 30000 bytes. That because it accepts comments. You can remove that by setting $cfws to $fws and it shrinks to about 6000 bytes. Conformity checking is absolutely and strictly referring to RFC2822. Have fun and email me if you have any enhancements!

Chủ Đề