XML technologies / Regular expressions / PHP / The preg functions / preg_match_all

(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)

preg_match_all(pattern, suchstring, treffer [, flags [, offset ]])

 

Parameters

pattern

The Pattern parameter: a regex with delimiters and optional modifiers (see The Pattern parameter).

suchstring

The text to search.

treffer

Variable receiving match data; mandatory.

flags

Optional flags controlling matching behavior. Possible values:

PREG_OFFSET_CAPTURE (see PREG_OFFSET_CAPTURE with preg_match_all)

and/or one of the following flags:

PREG_PATTERN_ORDER (see PREG_PATTERN_ORDER ordering, the default)
PREG_SET_ORDER (see PREG_SET_ORDER ordering)

offset

Zero-based subject-string offset at which to start searching, as with preg_match; see The offset parameter.

 

Return value

preg_match_all returns the number of successful matches.

 

Explanation

preg_match_all essentially works like preg_match, but the regex engine repeatedly searches after each success until a search fails. Every successful match generates an array of data, so the treffer variable ultimately holds an array of arrays, each inner array describing one match.

A simple example:

if (preg_match_all('/<title>/i', $html, $alle_treffer) > 1)
  print "Hoppla, die Webseite hat mehrere <title>-Tags!\n";

With preg_match_all, the third argument, the variable receiving match data, is mandatory, unlike with preg_match. That is why this example includes $alle_treffer although it is not otherwise used.

 

Empty match or no match

preg_match returns an empty string in the $treffer array when the corresponding group did not participate, subject to the previously mentioned removal of trailing empty elements from $treffer. A subexpression can also match an empty string, however. I would therefore prefer NULL for groups that did not participate.

I therefore developed a variant of preg_match with that behavior, called reg_match. It performs the actual search with PREG_OFFSET_CAPTURE, obtaining detailed capture information. This is used to construct the $treffer array with NULL in the appropriate elements:

function reg_match($regex, $suchstring, &$treffer, $offset = 0)
{
    $resultat = preg_match($regex, $suchstring, $treffer,
                           PREG_OFFSET_CAPTURE, $offset);
    if ($resultat) {
        $f = create_function('&$X', '$X = $X[1] < 0 ?  NULL : $X[0];');
        array_walk($treffer, $f);
    }
    return $resultat;
}

The $treffer array returned by reg_match matches the original preg_match without the PREG_OFFSET_CAPTURE flag, except that every group not participating in the complete match now has NULL.

 

Collecting match data

The other, crucial difference from preg_match concerns how results are returned. preg_match performs only one search, so the $treffer variable holds data for only one match. preg_match_all continues after each success, collecting every match’s data. To emphasize this, instead of $treffer I use the variable name $alle_treffer when discussing preg_match_all.

You can ask preg_match_all to arrange match data in $alle_treffer in either of two orders, selected using PREG_PATTERN_ORDER or PREG_SET_ORDER.

 

PREG_PATTERN_ORDER ordering, the default

The next example uses PREG_PATTERN_ORDER, which I call lined-up ordering. This is the default, so no explicit fourth argument is supplied.

$suchstring = "
Hans A. Schmid
Lisa B. Meier";

/* Kein viertes Argument, also Voreinstellung PREG_PATTERN_ORDER */
preg_match_all('/^(\w+) (\w\.) (\w+)$/m', $suchstring, $alle_treffer);

This produces a $alle_treffer array containing:

array
(
  /* $alle_treffer[0] ist ein Array mit allen Gesamttreffern */
  0 => array ( 0 => "Hans A. Schmid",  /* Gesamter Treffertext des ersten Treffers */
               1 => "Lisa B. Meier"    /* Gesamter Treffertext des zweiten Treffers */ ),

  /* $alle_treffer[1] ist ein Array, das alle vom 1. Klammerpaar eingefangenen Texte enthält */
  1 => array ( 0 => "Hans",  /* 1. Klammertext aus dem ersten Treffer */
               1 => "Lisa"   /* 1. Klammertext aus dem zweiten Treffer */ ),

  /* $alle_treffer[2] ist ein Array, das alle vom 2. Klammerpaar eingefangenen Texte enthält */
  2 => array ( 0 => "A.",    /* 2. Klammertext aus dem ersten Treffer */
               1 => "B."     /* 2. Klammertext aus dem zweiten Treffer */ ),

  /* $alle_treffer[3] ist ein Array, das alle vom 3. Klammerpaar eingefangenen Texte enthält */
  3 => array ( 0 => "Schmid", /* 3. Klammertext aus dem ersten Treffer */
               1 => "Meier"   /* 3. Klammertext aus dem zweiten Treffer */ )
)

Two matches were found, each with complete matched text and three captures. I call this lined-up because all complete matches share one array, $alle_treffer[0], while the first captures share another, $alle_treffer[1], and so on.

The default ordering is changed with PREG_SET_ORDER.

 

PREG_SET_ORDER ordering

I call the other ordering stacked, enabled with PREG_SET_ORDER. All data from the first match go into $alle_treffer[0], those from the second into $alle_treffer[1], and so on. It is like manually scanning the subject with preg_match and appending each match’s data to $alle_treffer.

Here is the PREG_SET_ORDER version of the preceding example:

$suchstring = "
Hans A. Schmid
Lisa B. Meier";

preg_match_all('/^(\w+) (\w\.) (\w+)$/m', $suchstring, $alle_treffer, PREG_SET_ORDER);

It produces a $alle_treffer array with these values:

array
(
  /* $alle_treffer[0] ist ganz analog zu $treffer bei preg_match */
  0 => array ( 0 => "Hans A. Schmid", /* Gesamter Treffertext aus dem ersten Treffer */
               1 => "Hans",           /* Text vom 1. Klammerpaar des ersten Treffers */
               2 => "A.",             /* Text vom 2. Klammerpaar des ersten Treffers */
               3 => "Schmid"          /* Text vom 3. Klammerpaar des ersten Treffers */ ),

  /* Auch $alle_treffer[1] ist ganz analog zu $treffer bei preg_match */
  1 => array ( 0 => "Lisa B. Meier",  /* Gesamter Treffertext aus dem zweiten Treffer */
               1 => "Lisa",           /* Text vom 1. Klammerpaar  des zweiten Treffers */
               2 => "B.",             /* Text vom 2. Klammerpaar  des zweiten Treffers */
               3 => "Meier"           /* Text vom 3. Klammerpaar  des zweiten Treffers */ )
)

A short summary of the two result orders:

 

Order

Flag

Description and example

Lined up

PREG_PATTERN_ORDER

Corresponding subresults from each match are grouped together.
$alle_treffer[$klammer_num][$treffer_num]

Stacked

PREG_SET_ORDER

All data from one match are grouped together.
$alle_treffer[$treffer_num][$klammer_num]

 

PREG_OFFSET_CAPTURE with preg_match_all

The flag PREG_OFFSET_CAPTURE works with preg_match_all just as with preg_match. Every string in the $alle_treffer array becomes a two-element array containing the matched text and its byte offset from the subject’s beginning. The variable $alle_treffer is thus an array of arrays of arrays, quite complex. To use both PREG_OFFSET_CAPTURE and PREG_SET_ORDER, combine them with bitwise OR:

preg_match_all($pattern, $suchstring, $alle_treffer,
               PREG_OFFSET_CAPTURE | PREG_SET_ORDER);

 

preg_match_all with named subexpressions

Named capturing groups add extra elements to $alle_treffer indexed by name, as with preg_match. After

$suchstring = "
Hans A. Schmid
Lisa B. Meier";
/* Kein viertes Argument, also Voreinstellung PREG_PATTERN_ORDER */
preg_match_all('/^(?P<Vorname>\w+) (?P<Initial>\w\.) (?P<Famname>\w+)$/m',
               $suchstring, $alle_treffer);

, $alle_treffer contains:

array
(
    0         => array ( 0 => "Hans A. Schmid",  1 => "Lisa B. Meier" ),
    "Vorname" => array ( 0 => "Hans",     1 => "Lisa"   ),
    1         => array ( 0 => "Hans",     1 => "Lisa"   ),
    "Initial" => array ( 0 => "A.",       1 => "B."     ),
    2         => array ( 0 => "A.",       1 => "B."     ),
    "Famname" => array ( 0 => "Schmid",   1 => "Meier" ),
    3         => array ( 0 => "Schmid",   1 => "Meier" )
)

The same example with PREG_SET_ORDER

preg_match_all('/^(?P<Vorname>\w+) (?P<Initial>\w\.) (?P<Famname>\w+)$/m',
               $suchstring, $alle_treffer, PREG_SET_ORDER);

produces a $alle_treffer array containing:

array
(
    0 => array ( 0       => "Hans A. Schmid",
                 Vorname => "Hans",
                 1       => "Hans",
                 Initial => "A.",
                 2       => "A.",
                 Famname => "Schmid",
                 3       => "Schmid" ),
    1 => array ( 0       => "Lisa B. Meier",
                 Vorname => "Lisa",
                 1       => "Lisa",
                 Initial => "B.",
                 2       => "B.",
                 Famname => "Meier",
                 3       => "Meier" )
)

Personally, I would prefer named groups to omit numeric elements, making results cleaner and smaller. But their presence does not require us to use them.

  

 

 

 

German edition copyright © 2008 by O’Reilly Verlag GmbH & Co. KG
You may print the online version for private use.
Otherwise, this chapter from "Reguläre Ausdrücke" is subject to the same terms as the bound edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, storage and processing in electronic systems.

O’Reilly Verlag GmbH & Co. KG, Balthasarstr. 81, 50670 Köln

back to top