Easy Tutorial
❮ Php Switch Func Array Map ❯

PHP preg_match_all() Function

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 in subject for all matches to the pattern 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 end of the last match.

Parameter descriptions:

Return Value

Returns the number of full pattern matches (which might be zero), or FALSE if an error occurred.

Example

Find content within <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]);
?>

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 back-reference. This tells PCRE that it must match the second set of parentheses (here ([\w]+))
// with the result. Two backslashes are used because this is a double-quoted string.
$html = "<b>bold text</b>&lt;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";
}
?>

Execution result is as follows:

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

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

PHP Regular Expressions (PCRE)

❮ Php Switch Func Array Map ❯