XML technologies / Regular expressions / PHP / The preg functions / preg_match
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
preg_match(pattern, suchstring [, treffer [, flags [, offset ]]])
Parameters
pattern
The Pattern parameter: a delimited regex with optional modifiers (see The Pattern parameter).
suchstring
The text to search.
treffer
Optional variable containing match data.
flags
Optional flags affecting matching behavior. Currently only one is defined,
PREG_OFFSET_CAPTURE(see Extracting match details: PREG_OFFSET_CAPTURE).
offset
Zero-based offset where searching begins (see The offset parameter). The German PHP documentation calls it Versatz .
Return value
True if a match is found; otherwise false.
Explanation
In its simplest form,
preg_match($pattern, $suchstring)
the function preg_match returns a boolean indicating whether the regex in $pattern matches anywhere in $suchstring. Here are some examples:
if (preg_match('/\.(jpe?g|png|gif|bmp)$/i', $url)) {
/* Offenbar eine URL von einem Bild */
}if (preg_match('{^https?://}', $uri)) {
/* Protokoll-Teil des URI ist http oder https */
}if (preg_match('/\b MSIE \b/x', $_SERVER['HTTP_USER_AGENT'])) {
/* Der verwendete Browser ist IE */
}Using match data
The optional third argument to preg_match is a variable receiving match data. Any variable works; my examples use “$treffer”. Even without a specific example, when I write “$treffer”, I mean the variable passed as the third argument to preg_match.
After a successful search, preg_match returns true and sets $treffer as follows:
$treffer[0] $treffer[1] $treffer[2] ...to the entire matched text
to the text matched by the first capturing group
to the text matched by the second capturing group
Named captures are returned too. An example follows in the next section.
Here is an example already seen under Practical regex techniques (see Extracting filenames from a pathname):
/* Dateinamen aus einem vollen Pfadnamen extrahieren */
if (preg_match('{ / ([^/]+) $}x', $pfad, $treffer))
$DateiName = $treffer[1];Inspect the $treffer variable (whatever its name) only if preg_match returned true . False is returned if no match is found or an error occurs (invalid pattern syntax, flags, etc.). Some errors clear $treffer, leaving an empty array. Others leave $treffer unchanged, with data from the previous successful search. Thus, a nonempty $treffer array does not prove success.
Here is a more complex example with three capturing groups:
/* Protokoll, Hostname und Port aus einer URL herausholen */
if (preg_match('{^(https?):// ([^/:]+) (?::(\d+))? }x', $url, $treffer))
{
$proto = $treffer[1];
$host = $treffer[2];
$port = $treffer[3] ? $treffer[3] : ($proto == "http" ? 80 : 443);
print "Protokoll: $proto\n";
print "Hostname : $host\n";
print "Port : $port\n";
}Trailing empty match elements are omitted
If a capturing group does not participate in the match, its $treffer array element receives an empty string (note: if you expect NULL, see Empty match or no match). However, trailing empty elements in $treffer are omitted entirely. In the preceding example, ˹(\d+)˼ may participate in the match, making $treffer[3] a number. If not, the element $treffer[3] does not exist.
Named captures
Consider the same example with named captures (see Named captures). The regex becomes longer but more self-explanatory:
/* Protokoll, Hostname und Port aus einer URL herausholen */
if (preg_match('{^(?P<proto> https? ) ://
(?P<host> [^/:]+ )
(?: :(?P<port> \d+ ) )? }x', $url, $treffer))
{
$proto = $treffer['proto'];
$host = $treffer['host'];
$port = $treffer['port'] ? $treffer['port'] : ($proto=="http"?80:443);
print "Protokoll: $proto\n";
print "Hostname : $host\n";
print "Port : $port\n";
}More descriptive names eliminate the need to copy $treffer into individual variables. In such cases, choose a name other than $treffer, for example:
/* Protokoll, Hostname und Port aus einer URL herausholen */
if (preg_match('{^(?P<proto> https? )://
(?P<host> [^/:]+ )
(?: :(?P<port> \d+ ) )? }x', $url, $UrlInfo))
{
if (! $UrlInfo['port'])
$UrlInfo['port'] = ($UrlInfo['proto'] == "http" ? 80 : 443);
echo "Protokoll: ", $UrlInfo['proto'], "\n";
echo "Hostname : ", $UrlInfo['host'], "\n";
echo "Port : ", $UrlInfo['port'], "\n";
}Named captures still produce numbered entries in $treffer .
If the preceding program searches $url ›"http://regex.info/"‹, then $UrlInfo contains:
array
(
0 => 'http://regex.info',
'proto' => 'http',
1 => 'http',
'host' => 'regex.info',
2 => 'regex.info'
)Duplicating entries wastes memory, the price of the convenience and clarity of named captures. I advise against mixing named and numbered captures, except $treffer[0] for the entire match.
Note that the elements 3 and ›port‹ were not printed: they did not participate and were omitted as trailing empty entries in $treffer (see Trailing empty match elements are omitted).
Although numeric capture names are possible, for example ˹(?P<2>...)˼, strongly avoid them. PHP 4 and PHP 5 handle this paradox differently, neither as one would expect. Avoiding numeric capture names is best.
Extracting match details: PREG_OFFSET_CAPTURE
When preg_match receives PREG_OFFSET_CAPTURE as its fourth argument (the only currently allowed value), each $treffer array element becomes a two-element subarray: the captured text, then its offset from the subject's beginning (or -1 if the group did not participate).
Offsets are zero-based and always relative to the subject's beginning, even when the fifth $offset argument specifies a starting offset. Offsets are measured in bytes even with the u modifier (see PHP-specific modifiers).
Consider HREF in a link tag. HTML attribute values may be double-quoted, single-quoted, or unquoted. The following regex extracts these forms with its first, second, or third capturing group:
preg_match('/href \s*=\s* (?: "([^"]*)" | \'([^\']*)\' | ([^\s\'">]+) )/ix',
$tag,
$treffer,
PREG_OFFSET_CAPTURE);If $tag has the value
<a name=bloglink href='http://regex.info/blog/' rel="nofollow">
, a match is found and $treffer contains:
array
(
/* Daten für den gesamten Treffer */
0 => array ( 0 => "href='http://regex.info/blog/'",
1 => 17 ),
/* Daten für das erste einfangende Klammerpaar */
1 => array ( 0 => "",
1 => -1 ),
/* Daten für das zweite einfangende Klammerpaar */
2 => array ( 0 => "http://regex.info/blog/",
1 => 23 )
)$treffer[0][0] is the entire matched text, and $treffer[0][1] indicates its starting position in $tag.
The string in $treffer[0][0] could also be obtained with:
substr($tag, $treffer[0][1], strlen($treffer[0][0]));
$treffer[1][1] is -1, indicating that the first group did not participate. Neither did the third, but trailing empty elements of $treffer are not returned (see above, Trailing empty match elements are omitted).
The offset parameter
If preg_match receives the argument offset , the regex engine starts searching at the byte at that offset. Negative offsets are measured from the end. By default, searching starts at offset 0, the subject's beginning.
The offset must be in bytes, even with the u modifier. An invalid offset inside a multibyte sequence makes the search fail without warning.
When searching from a nonzero offset, the metacharacter ˹^˼ still refers to the beginning of the entire subject. The offset merely sets where the attempt starts; lookbehind can see preceding text, for example.
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