HomeCoding & Programming

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

Like Tweet Pin it Share Share Email

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()

ereg('\.([^\.]*$)', $file_name, $extension);

becomes

preg_match('/\.([^\.]*$)/', $file_name, $extension);

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()

$file_name = ereg_replace('[^A-Za-z0-9_]', '', $file_name);

becomes

 
 // 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.

eregi('\.([^\.]*$)', $file_name, $extension);

becomes

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

Comments (1)

Comments are closed.