XML technologies / Regular expressions / PHP / The preg functions / preg_replace
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
preg_replace(pattern, ersatztext, suchstring [, limit [, anzahl ]])
Parameters
pattern
The Pattern parameter: a regex with delimiters and optional modifiers. pattern may also be an array of pattern strings.
ersatztext
Replacement string, or an array of replacements if pattern is an array. With the e modifier, strings are interpreted as PHP statements (see Simple preg_replace with one pattern, replacement, and subject).
suchstring
Subject text, or an array of subjects processed in order.
limit
Optional maximum replacement count (see Simple preg_replace with one pattern, replacement, and subject).
anzahl
Optional variable receiving the actual replacement count, from PHP 5 onward (see Simple preg_replace with one pattern, replacement, and subject).
Return value
If suchstring is a string, the result is a string: a copy of suchstring with replacements. If suchstring is an array, the result is an array of modified suchstring elements.
Explanation
PHP provides several methods of search and replace. For literal patterns, prefer str_replace and str_ireplace; more complex tasks need preg_replace.
Web forms often demand phone or credit-card numbers with no spaces or hyphens, forcing users to type unstructured digits. (Note: my brother collected such sites in a “Hall of Shame”.) The programmer can easily remove this burden:
$karten_nummer = preg_replace('/\D+/', '', $karten_nummer);
/* $karten_nummer enthält jetzt nur Ziffern oder ist leer */Here, preg_replace removes nondigits. More explicitly, preg_replace copies $karten_nummer and replaces nondigit runs with an empty string. The result becomes the new $karten_nummer.
Simple preg_replace with one pattern, replacement, and subject
Each of the first three arguments (pattern, ersatztext and suchstring) may be strings or arrays. Usually all are strings: preg_replace copies the subject and repeatedly finds and replaces matches until failure.
In replacement text, ›$0‹ means the whole match, ›$1‹ capture one, ›$2‹ capture two, and so on. These are notation, not language variables, telling preg_replace to preprocess replacements. Braces may enclose the number, as in ›${0}‹ or ›${1}‹, needed when another digit follows.
This highlights uppercase HTML words with <b> tags:
$html = preg_replace('/\b[A-Z]{2,}\b/', '<b>$0</b>', $html);With the e modifier, allowed only with preg_replace, replacement text is executed as PHP after substituting ${0}, ${1}, etc.; the result is the actual replacement.
Extend the example by lowercasing the word highlighted with <b>:
$html = preg_replace('/\b[A-Z]{2,}\b/e',
'strtolower("<b>$0</b>")',
$html);If the match is ›HALLO‹, it replaces ›$0‹, producing ›strtolower("<b>HALLO</b>")‹. Executing this PHP produces replacement text ›<b>hallo</b>‹.
With the e modifier, interpolated dollar-number values escape single and double quotes with backslashes, preventing invalid PHP.
With the e modifier and ›$0‹, ›$1‹, etc., single-quote replacement strings to avoid premature interpolation.
This resembles PHP's htmlspecialchars() function:
$ersatztext = array ('&' => '&',
'<' => '<',
'>' => '>',
'"' => '"');
$neuer_suchstring = preg_replace('/[&<">]/eS', '$ersatztext["$0"]', $suchstring);Here the ersatztext must be single-quoted so $ersatztext is interpolated only when preg_replace executes the PHP replacement, rather than before preg_replace is called.
The S modifier improves efficiency here (see The S modifier).
The fourth argument to preg_replace caps replacements per regex and subject. The default -1 means unlimited.
From PHP 5, the fifth argument receives the actual count. Inspecting this is more efficient than comparing before and after strings to detect changes: use anzahl.
preg_replace with multiple patterns, subjects, and replacements
Earlier, suchstring was a single subject string. It can be an array; then each string is processed and the result is also an array.
Independently, parameters pattern and ersatztext may be arrays too. The combinations are:
Pattern | Replacement | Effect |
|---|---|---|
String | String | Apply pattern, replacing every match |
Array | String | Apply patterns in order, replacing every match |
Array | Array | Apply patterns in order with corresponding replacements |
String | Array | (not allowed) |
If suchstring is an array, each subject is replaced and an array returned.
Note that limit applies to each pattern/subject pair, not their aggregate. But anzahl returns the total count over all patterns and subjects.
Here both pattern and ersatztext are arrays. Like PHP's htmlspecialchars(), the code escapes special characters for HTML:
$html = preg_replace(
array('/&/', '/</', '/>/', '/"/' ), /* Nach diesen suchen ... */
array('&', '<', '>', '"'), /* ... durch diese ersetzen ... */
$text /* ... in einer Kopie hiervon */
);A $text of
AT&T --> "baby Bells"becomes:
AT&T --> "baby Bells"Prebuilt arrays work identically:
$pattern = array('/&/', '/</', '/>/', '/"/' );
$ersatztexte = array('&', '<', '>', '"');
$html = preg_replace($pattern, $ersatztexte, $text);Array arguments to preg_replace save explicit loops but add no functionality. Patterns run sequentially, not in parallel; built-in loops may be faster and clearer.
All three arguments as arrays:
$resultat_array = preg_replace($regex_array, $ersatztext_array, $suchstring_array);Approximately equivalent PHP:
$resultat_array = array();
foreach ($suchstring_array as $suchstring)
{
reset($regex_array); // Diese zwei Arrays werden in der internen
reset($ersatztext_array); // Reihenfolge von PHP abgearbeitet.
while (list(,$regex) = each($regex_array))
{
list(,$ersatztext) = each($ersatztext_array);
// Regex und Ersatztext sind vorhanden, auf einen einzelnen Suchstring anwenden ...
$suchstring = preg_replace($regex, $ersatztext, $suchstring);
}
// Suchstring wurde von allen Regex bearbeitet, der veränderte Text wird jetzt an das ...
$resultat_array[] = $suchstring; // ... Resultat-Array angehängt.
}Array element order
If pattern and ersatztext are arrays, they follow PHP’s natural order, usually insertion order. The first inserted pattern pairs with the first ersatztext, etc. Literal arrays using array() work as expected:
$suchstring = "Dieser Satz hat 8 Wörter und 39 Zeichen";
$resultat = preg_replace(array('/[a-zäöüß]+/i', '/\d+/'),
array('Wort<$0>', 'Zahl<$0>'),
$suchstring);
print "$resultat\n";The regex ˹[a-zäöüß]+˼ pairs with ›Wort<$0>‹ and ˹\d+˼ with ›Zahl<$0>‹, yielding:
Wort<dieser> Wort<satz> Wort<hat> Zahl<8> Wort<wörter> Wort<und> Zahl<39> Wort<zeichen>
But if pattern or ersatztext were built incrementally, their internal order may differ from numeric index order. The earlier explicit code uses each to follow internal order regardless of numeric keys.
If unsure whether pattern and ersatztext share insertion order, sort by ksort() to ensure a common defined order.
If both pattern and ersatztext are arrays but pattern contains more entries, missing ersatztext entries default to empty strings.
Regex order in pattern matters because processing is sequential. This example swaps regexes in pattern and corresponding replacements in ersatztext .
$suchstring = "Dieser Satz hat 8 Wörter und 39 Zeichen";
$resultat = preg_replace(array('/\d+/', '/[a-zäöüß]+/i'),
array('Zahl<$0>', 'Wort<$0>' ),
$suchstring);
print "$resultat\n";Does the output change? See Solution 16.
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