Fix `ereg is deprecated` errors in PHP 5.3

If you upgraded to PHP 5.3, chances are high you’re going to run into a few warnings or deprecated function messages.
An example is the ereg family of functions, which are gone for good, as they were slower and felt less familiar than the alternative Perl-compatible preg family.

To migrate ereg():

ereg('\.([^\.]*$)', $this->file_src_name, $extension);

becomes

preg_match('/\.([^\.]*$)/', $this->file_src_name, $extension);

Notice that I 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():

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

becomes

$this->file_dst_name_body = preg_replace('/[^A-Za-z0-9_]/', '', $this->file_dst_name_body);

Again, I just added delimiters to the pattern.
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.

Basically, to make the pattern match characters in a case-insensitive way, append i after the delimiter:

eregi('\.([^\.]*$)', $this->file_src_name, $extension);

becomes

preg_match('/\.([^\.]*$)/i', $this->file_src_name, $extension);

Author: Guillermo Rauch
Advertisements

2 Comments

  1. March 18, 2010 at 10:59 pm

    […] Fix `ereg is deprecated` errors in PHP 5.3 (scvinodkumar.wordpress.com) […]

  2. August 9, 2014 at 3:56 am

    An outstanding share! I have jist forwarded this onto a co-worker who had been doing a
    little research on this. And he in fact ordered me lunch because I found it for him…
    lol. So let me reword this…. Thanks for thhe meal!! But yeah, thanks for spendung the time
    to talk about this matter here on your web site.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: