PHP's /e modifier is deprecated, use preg_replace_callback instead

Josh Sherman
1 min read
Software Development PHP

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:

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]+ ?/',
		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.

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles