I’ve discussed the use of preg_replace_callback in the past in regard to passing variables to anonymous functions but never touched on how to use preg_replace_callback or the fact that the /e modifier has been deprecated in PHP 5.5+. Even though /e still works in PHP 5.5 in the near future it won’t be supported at all so migrating away from /e to using preg_replace_callback is highly recommended. For more information regarding the potential for security vulnerabilities by using the /e modifier go here: http://us2.php.net/manual/en/reference.pcre.pattern.modifiers.php#reference.pcre.pattern.modifiers.eval

The function preg_replace_callback allows you to specify a callback function either by name (as a string) or in the form of an anonymous function. First let’s take a look at using a user function which is how you would want to do things if you needed to use the function in different locations in your code or simply wanted to have the function available for standalone use. The follow example grabs the first word from a string and uppercases it:

function uc1stWord($matches)
{
	return strtoupper($matches[0]);
}

echo preg_replace_callback('/^[a-z]+ ?/', 'uc1stWord', 'this is a sentence.');

Here is the same example utilizing an anonymous function:

echo preg_replace_callback(
	'/^[a-z]+ ?/',
	function(matches)
	{
		return strtoupper($matches[0]);
	},
	'this is a sentence.'
);

A few things to note, the $matches array contains all of the matches indexed by how they are nested. If you are using paretheses in your regular expression the value you are looking for may end up being in $matches[1] instead of $matches[0]. When in doubt, vardump() the $matches array.





Did you enjoy this post?

Cool if I slip into your inbox with more?
Full posts, 1-2 times per week: