How to fix ‘Function eregi() is deprecated’ in PHP 5.3.0

Published on Author bloggeroneLeave a comment
Problem or the issue:

Previously eregi used to validate email address input using regular expression.

if(!eregi("^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$", $str)) {
   $msg = 'email is not valid';
   } else {
   $valid = true;
}

That would return true if given email address matches to username@domain.ext pattern. Unfortunately, after upgrading PHP to the new version (5.3.0), it won’t work properly and throw notices. This is because eregi is one of several functions that are deprecated in the new version (5.3.x) of PHP.

Solution:

Use preg_match with the ‘i’ modifier instead. i means that regular expression is case insensitive. So the code will be this:

if(!preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $str)) {
 $msg = 'email is not valid';
 } else {
 $valid = true;
}

To summarize, the preg_match, forward slash, and i are the differences.

Comments

comments

Leave a Reply

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