XML technologies / Regular expressions / PHP / The preg functions / preg_replace_callback
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
preg_replace_callback(pattern, callback, suchstring [, limit [, anzahl ]])
Parameters
pattern
The Pattern parameter: a regex with delimiters and optional modifiers (see The pattern parameter). pattern may also be an array of Pattern strings.
callback
A PHP callback function called on every successful match to produce the replacement text.
suchstring
The text to search. An array of subject strings is also allowed; its elements are processed in order.
limit
An optional number specifying the maximum number of replacements (see Simple preg_replace with one pattern, replacement, and subject string).
anzahl
An optional variable receiving the actual number of replacements, available from PHP 5.1.0 (see Simple preg_replace with one pattern, replacement, and subject string).
Return value
If suchstring is a single string, so is the result: a copy of suchstring with replacements applied. If suchstring is a string array, the result is likewise a string array whose elements are modified versions of the suchstring elements.
Explanation
The function preg_replace_callback resembles preg_replace, but replaces the replacement-text argument with a callback. Its behavior resembles preg_replace with the e modifier (see Simple preg_replace with one pattern, replacement, and subject string), but is more efficient and easier to read when the replacement expression is complex.
Consult the PHP documentation for callback details. Briefly, a PHP callback is a function invoked in predefined circumstances with predefined arguments. Its return value is processed by the function invoking it. In preg_replace_callback, the callback runs when a match is found, with exactly one argument: the $treffer array. Its return value is used by preg_replace_callback as replacement text.
The callback argument can take several forms. It may be a string naming the function, or an anonymous function created with PHP’s built-in create_function. Examples of both follow shortly. A third form, not explored in this book, serves object-oriented programming: a class name and one of its methods.
Here is the example from Simple preg_replace with one pattern, replacement, and subject string, this time using preg_replace_callback and a callback, whose name is passed as a string.
$ersatztext = array ('&' => '&',
'<' => '<',
'>' => '>',
'"' => '"');
/*
* Im Parameter $treffer werden die Daten des gerade gefundenen Treffers übergeben.
* $treffer[0] ist dabei der Text, der in HTML umgewandelt werden soll.
* Weil wir wissen, unter welchen Umständen diese Funktion aufgerufen wird, können wir
* auf eine Prüfung der Argumente verzichten.
*/
function text2html_callback($treffer)
{
global $ersatztext;
return $ersatztext[$treffer[0]];
}
$suchstring_neu = preg_replace_callback('/[&<">]/S', /* Pattern */
"text2html_callback", /* Callback */
$suchstring);Called with a $suchstring such as
"R&B" ist "Rhythm and Blues"
, this produces:
"R&B" ist "Rhythm and Blues"Here, text2html_callback is an ordinary PHP function designed as a callback for preg_replace_callback. Its sole argument is the $treffer array. This name can of course be changed; $treffer is merely conventional.
For completeness, here is a version using an anonymous function created with PHP’s built-in create_function. It assumes the same $ersatztext array as above. The callback body is also identical, but instead of naming the function, its code is passed anonymously and can be called only by preg_replace_callback :
$suchstring_neu = preg_replace_callback('/[&<">]/S',
create_function('$treffer',
'global $ersatztext;
return $ersatztext[$treffer[0]];'),
$suchstring);Callback or e modifier?
For simple tasks, preg_replace with the e modifier in the Pattern argument is generally clearer than preg_replace_callback. Efficiency may nevertheless favor callbacks. With the e modifier, the replacement argument is reinterpreted as PHP code for every match. With preg_replace_callback this is unnecessary because the callback is compiled only once.
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