The php Function Preg_Replace_Callback
The php function preg_replace_callback is a powerful tool that goes beyond standard regular expression find/replace functionality. It allows developers to use custom callback functions for each matched string, making it possible to easily implement more complex templating logic. This article provides a clear explanation of this functionality together with carefully crafted examples that illustrate some of its most common uses.
Preg_replace_callback is the newest member of the PHP family of regular expression functions and offers a great deal of versatility for developers that need to modify strings based on matching patterns. Its flexibility makes it an indispensable tool when developing templating code.
Like its sister function, preg_replace, it accepts an array of data keys as the subject and an argument that specifies the pattern to search for and the replacement string. If the pattern contains delimiters such as spaces or backslashes that need to be escaped, the preg_replace_callback() function also escapes them for you. However, the time it takes to process a large array will increase linearly as the number of data keys increases. This is a result of the fact that all methods for replacing placeholders in a template (including the str_replace method) work on an O(n) algorithm and need to check each data key for matching patterns.