ereg, eregi, ereg_replace is Deprecated

Since upgrading to PHP 5.3, there has been a lot of deprecated code that I’ve had to fix. Another of these is the family of ereg() eregi() and ereg_replace() – all of which can be replaced by preg_match(). While searching how to fix it, I came across a few sites that all gave similar results.

An example of some deprecated code would be:

ereg(‘\.([^\.]*$)’, $this->src_name, $variable);

The replacement for this is actually really easy – change it to preg_match and add a few characters to the start and end of the first variable (called delimiters):

preg_match(‘/\.([^\.]*$)/‘, $this->src_name, $variable);

Eregi is similar, here’s a before:

eregi(“^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$”, $str)

Here’s what it looks like afterwards:

preg_match(“/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/“, $str)

Finally, ereg_replace:

ereg_replace(‘[^A-Za-z0-9_]’, ”, $this->variable);

The replacement to it:

preg_replace(‘/[^A-Za-z0-9_]/i’, ”, $this->variable);

If you are using eregi (the case-insensitive version of ereg), you’ll notice there is no pregi function. This is because this functionality is handled by RegExp modifiers. To make the pattern match characters in a case-insensitive way, append i after the delimiter, like this:

eregi(‘\.([^\.]*$)’, $this->variable, $anothervar);

preg_match(‘/\.([^\.]*$)/i‘, $this->variable, $anothervar)

Good luck!

Leave a Reply

Your email address will not be published. Required fields are marked *