Home >Backend Development >PHP Tutorial >How to Safely Replace PHP's Deprecated `preg_replace()` `/e` Modifier with `preg_replace_callback()`?
Regular expressions can be intimidating, especially when working with capturing groups and replacements. Let's decipher a replacement task from preg_replace() using the '/e' modifier:
public static function camelize($word) { return preg_replace('/(^|_)([a-z])/e', 'strtoupper("\2")', $word); }
Here, the goal is to capitalize the letter following '^' (beginning of the string) or '_' (underscore).
The '/e' modifier evaluates the replacement string as PHP code. '2' refers to the second captured group, which is the small letter following the '^' or '_'. This modifier, however, is being deprecated for security reasons.
preg_replace_callback() offers a safer alternative by providing a callback function instead of a replacement string:
return preg_replace_callback('/(^|_)([a-z])/', function($matches) { return strtoupper($matches[2]); }, $word);
The anonymous function takes an array of matches as an argument. Here, $matches[1] represents the '^' or '_' and $matches[2] the letter to be capitalized.
Note that the '/e' modifier needs to be removed when using preg_replace_callback(). The above pattern simplifies to:
return preg_replace_callback('/(^|_)([a-z])/', function($matches) { return strtoupper($matches[2]); }, $word);
Anonymous functions only have access to variables explicitly imported using the 'use' keyword.
The above is the detailed content of How to Safely Replace PHP's Deprecated `preg_replace()` `/e` Modifier with `preg_replace_callback()`?. For more information, please follow other related articles on the PHP Chinese website!