How to fix ‘Function ereg() is deprecated’ in PHP 5.3.x?

If you upgraded your PHP version to PHP 5.3.x, you will get few warnings or deprecated function messages like function ereg() is deprecated in php 5.3.x. You can find the full list of functions that are deprecated by following URL Deprecated features in PHP 5.3.x

ereg family functions are deprecated in PHP 5.3.0 or later,as these were slower and felt less familiar than the alternative Perl-compatible preg family.

To migrate ereg()

[php]ereg(‘\.([^\.]*$)’, $file_name, $extension);[/php]


[php]preg_match(‘/\.([^\.]*$)/’, $file_name, $extension);[/php]

Notice that wrapped the pattern (\.([^\.]*$)) around / /, which are RegExp delimiters.
If you find yourself escaping / too much (for an URL for example), you might want to use the # delimiter instead.

To migrate ereg_replace()

[php]$file_name = ereg_replace(‘[^A-Za-z0-9_]’, ”, $file_name);[/php]


// preg_replace($pattern, $replacement, $string);
$file_name = preg_replace(‘/[^A-Za-z0-9_]/’, ”, $file_name);


If you are using eregi functions (which are the case-insensitive version of ereg), you’ll notice there’re no equivalent pregi functions.
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.

[php]eregi(‘\.([^\.]*$)’, $file_name, $extension);[/php]


[php]preg_match(‘/\.([^\.]*$)/i’, $file_name, $extension);[/php]

One thought on “How to fix ‘Function ereg() is deprecated’ in PHP 5.3.x?”

Comments are closed.