XML technologies / Regular expressions / PHP / The preg programming interface / The “Pattern” parameter
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
The first parameter of every preg function is the pattern, consisting of the regex surrounded by delimiters and optionally followed by modifiers. In the first example in The preg programming interface, the pattern is '/<table\b/i'; that is, the actual regex is ˹<table\b˼, slashes serve as delimiters, and the i modifier, for case-insensitive matching, is enabled.
Single-quoted strings in PHP
Since regexes themselves very often contain backslashes, it is usually advantageous to write the Pattern argument as a single-quoted string. The different string-literal types in PHP were described in Features and dialects (see Strings in PHP). With single-quoted strings, you can almost always avoid doubling backslashes. PHP’s single-quoted strings recognize only two metasequences, for the quote itself and for backslash: ›\'‹ and ›\\‹.
You really need a larger number of backslashes only when searching for a backslash with ˹\\˼ in the regex. Each ˹\˼ must itself be escaped with a backslash, so a single backslash requires writing \\\\. Whew!
(The program example in The solution suffers from this kind of backslashitis.)
As a concrete example, consider a regex matching the drive-letter portion of a Windows pathname, a string such as ›C:\‹. A suitable regex is ˹^[A-Z]:\\$˼, but in a single-quoted string it must be written as: '^[A-Z]:\\\\$'.
In the lower table of Removing the directory from a pathname in Practical regex techniques, we used a Pattern argument containing three backslashes. The following examples help explain this:
print '/^.*\/'; Gibt aus: /^.*\/
print '/^.*\\/'; Gibt aus: /^.*\/
print '/^.*\\\/'; Gibt aus: /^.*\\/
print '/^.*\\\\/'; Gibt aus: /^.*\\/The first two versions produce the same result by different routes. In the first example, the sequence ›\/‹ has no special meaning in single-quoted strings, so both characters appear unchanged in the string’s value. In the second example, ›\\‹ is a metasequence for one backslash, producing ›\‹ in the string’s value. The ordinary slash follows it, as in the first example. The third and fourth examples behave analogously.
PHP also permits double-quoted strings, of course, but they are usually considerably less convenient. They have many metasequences of their own, all of which must be escaped when a regex metasequence is needed instead.
Delimiters
The preg functions require delimiters around the regex string because PHP’s developers closely followed Perl syntax, particularly its notation for pattern modifiers. Others consider this design decision mistaken, since modifiers could be specified differently and delimiters omitted. Delimiters can also cause problems; see the box The Unknown Modifier error.
Slashes are the usual delimiters, but any nonalphanumeric ASCII character except whitespace and backslash can be used. Common choices are ›!‹ and ›#‹.
If the first delimiter is an opening character:
{ ( < [
the second must be the corresponding closing character:
} ) > ]
Such paired delimiters can be nested, allowing a Pattern argument such as '((\d+))'. The outer parentheses are delimiters; only the inner pair belongs to the regex. This is more confusing than useful, though. Here I would not rely on it and would use something simpler, such as '/(\d+)/'.
A delimiter appearing inside the regex must be escaped with a backslash. Something like '/<B>(.*?)<\/B>/i' is therefore valid, but a version such as '!<B>(.*?)</B>!i' using ›!...!‹, or '{<B>(.*?)</B>}i' using ›{...}‹ as delimiters, is surely easier to read.
Pattern modifiers
After the closing delimiter, you may specify a series of modifiers, called pattern modifiers in the manual; some can also appear inside the regex itself. We have already encountered the case-insensitive modifier i . Here is a list of supported modifiers:
Table: pattern modifiers in PHP.
Modifier | Inline |
| Description |
|---|---|---|---|
|
| Ignore case | |
|
| Multiline mode, or enhanced line-anchor mode | |
|
| Dot matches all | |
|
| Free-spacing mode | |
|
| Regex and subject string are encoded in UTF-8. | |
|
| Enable PCRE’s extra options | |
|
| see Simple preg_replace with one pattern, replacement, and subject | Execute replacement text as PHP code, only with |
|
| see The S modifier | Use PCRE’s study optimization |
The following modifiers are rarely used: | |||
|
| Reverse the meanings of | |
|
| Match must begin at the current search position | |
|
|
| |
Modifiers inside the regex
Pattern modifiers can also be enabled and disabled inline, inside the regex. For example, ˹(?i)˼ enables case-insensitive matching, and ˹(?-i)˼ disables it again (see Mode modifiers).
A modifier remains in effect only until the end of the parenthesized expression containing it, or until the regex’s end if there are no such parentheses.
They can also be used as modifier scopes (see Parenthesized mode modifiers). For example, ˹(?i:...)˼ enables the i modifier only within that scope; ˹(?-sm:...)˼ disables the modifiers s and m within the specified scope.
Modifiers outside the regex
Modifiers may appear in any combination and order after the closing delimiter. Here, “si” enables case-insensitive and dot-matches-all modes:
if (preg_match('{<title>(.*?)</title>}si', $html, $treffer))PHP-specific modifiers
The table’s first four modifiers exist in almost every modern implementation and are discussed in Features and dialects (see Case-insensitive mode). The e modifier affects only preg_replace and is discussed in the relevant section (see Simple preg_replace with one pattern, replacement, and subject).
The modifier u treats both the regex and the subject as UTF-8. It does not change the bytes, only how the regex engine interprets them. Normally, without the u modifier, subject and regex are treated as 8-bit strings in the current locale (see POSIX: an attempt at standardization). Use the modifier only if the data is known to be UTF-8. Non-ASCII characters are represented in UTF-8 by several bytes, and the u modifier treats such a byte sequence as one character .
The X modifier enables extra PCRE functionality. Currently, it merely raises an error if a regex contains a backslash not belonging to a known metacharacter. For example, the sequence ˹\k˼ has no special meaning to PCRE and is normally treated simply as ˹k˼ : a backslash outside a known metasequence is ignored. With the X modifier enabled, an error is reported (“unrecognized character follows \”) and the program aborts.
Backslash-letter combinations unknown in current PHP and PCRE versions might acquire a meaning in future versions. For this reason, and for readability, it is sensible to use backslashes only where necessary. The X modifier is helpful here, as it can reveal typos and other errors.
The S modifier enables PCRE’s study option. Before matching, the regex is examined for optimization opportunities, which can yield enormous speed gains in certain clearly defined cases. This option is discussed in the efficiency section, The S modifier.
The remaining modifiers are rather esoteric and rarely used:
The A modifier forces a match to start where the search begins, as if the regex started with
˹\G˼. In the transmission analogy from How regex engines work, this disables the transmission’s shifting (see The transmission advances to the next character).The D modifier treats
˹$˼as˹\z˼(see Enhanced line-anchor mode, or multiline mode), so˹$˼matches only the subject’s end, not a newline immediately before it.The U modifier reverses greedy and lazy quantifiers:
˹*˼becomes˹*?˼and vice versa;˹+˼becomes˹+?˼and vice versa, and so on. In my view, this modifier’s primary purpose is to cause confusion, so I strongly advise against using it.
The Unknown Modifier errorMore than once during development, a program has suddenly reported “Unknown Modifier”. It turned out I had merely forgotten the Pattern parameter’s delimiters. For example, I wanted to test for an HTML tag:
The initial angle bracket was meant to match the tag’s beginning, but to Of course, the regex
Hindsight makes it obvious, of course, that delimiters are needed:
The trouble is that regexes are not the only things with modifiers. Unless I happen to be thinking of PHP pattern modifiers, it can take me a while to understand the error correctly. I feel rather foolish, but fortunately nobody knows I make such elementary mistakes. Newer PHP5 versions at least include the function’s name:
The function name points me in the right direction, leaving only the delimiters to add. Far more dangerous are cases where no error is reported. If the preceding example’s regex had been:
Then |
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