PHP preg_match_all() Function

PHP 正则表达式(PCRE)PHP Regular Expressions (PCRE)

The preg_match_all function is used to perform a global regular expression match.

Syntax

int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG_PATTERN_ORDER [, int $offset = 0 ]]] )

Searches subject for all matches to the regular expression given by pattern and outputs them to matches in the order specified by flags.

After the first match is found, subsequent searches continue from the position of the last match.

Parameter description:

  • $pattern: The pattern to search for, as a string.

  • $subject: The input string.

  • $matches: A multi-dimensional array that outputs all matching results as an output parameter. The array ordering is specified by flags.

  • $flags: Can be used with the following flags (note that PREG_PATTERN_ORDER and PREG_SET_ORDER cannot be used simultaneously):

    1. PREG_PATTERN_ORDER: Results are ordered so that $matches

    2. PREG_SET_ORDER: Results are ordered so that $matches

    3. PREG_OFFSET_CAPTURE: If this flag is passed, each found match will also include its offset relative to the target string when returned.

  • offset: Usually, the search starts from the beginning of the target string. The optional parameter offset is used to start searching from a specified position in the target string (in bytes).

Return Value

Returns the number of full matches (which may be 0), or FALSE if an error occurs.

Examples

Find content matching the <b> and </b> tags:

<?php $userinfo = "Name: <b>PHP</b> <br> Title: <b>Programming Language</b>"; preg_match_all ("/<b>(.*)<\/b>/U", $userinfo, $pat_array); print_r($pat_array[0]); ?>

The execution result is as follows:

Array
(
    [0] => <b>PHP</b>
    [1] => <b>Programming Language</b>
)

Find matching HTML tags (greedy):

<?php //\\2 is an example of a backreference. This tells PCRE that it must match the result captured by the second parenthesized group in the regular expression (here, ([\w]+)) //The matched result. Two backslashes are used here because double quotes are used. $html = "<b>bold text</b><a href=howdy.html>click me</a>"; preg_match_all("/(<([\w]+)[^>]*>)(.*?)(<\/\\2>)/", $html, $matches, PREG_SET_ORDER); foreach ($matches as $val) { echo "matched: " . $val[0] . "\n"; echo "part 1: " . $val[1] . "\n"; echo "part 2: " . $val[2] . "\n"; echo "part 3: " . $val[3] . "\n"; echo "part 4: " . $val[4] . "\n\n"; } ?>

The execution result is as follows:

matched: <b>bold text</b>
part 1: <b>
part 2: b
part 3: bold text
part 4: </b>

matched: <a href=howdy.html>click me</a>
part 1: <a href=howdy.html>
part 2: a
part 3: click me
part 4: </a>

PHP 正则表达式(PCRE)PHP Regular Expressions (PCRE)

Other Extensions