Question

I'm was using PHP eregi function, but I get the notice that it is deprecated. Here's my code:

!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))

Therefore I am trying to replace the function with the preg_match, but seems that I am unable to get the correct pattern for the preg_match, as I get error with the following code:

!preg_match("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))

Here's the error I get from above code:

Warning: preg_match(): No ending delimiter '^' found in

Thanks for any help.

Était-ce utile?

La solution

You need to use a delimiter at the beginning and end of your regex, commonly /:

!preg_match("/^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$/", trim($_POST['email']))

Manual entry: PCRE introduction / delimiters

Autres conseils

You need to delimit your regular expression:

preg_match("/^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$/",
            ^                                         ^

preg_match() wants you to use a delimiter at the start or end of a regex string:

preg_match("/^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$/", trim($_POST['email']))

The delimiter can be several characters, including ~, %, #, /, @, etcetera. Notice that when you pick a delimiter, if that character is used inside the regular expression, it must be escaped with a backslash character (\). For example, using the regex

http://[0-9a-z]+\.com

with the combination of the delimiter /, will require you to escape every occurence of /:

/http:\/\/[0-9a-z]+\.com/

See the PHP manual for more information.

Try it like,

!preg_match("/^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$/i", trim($_POST['email']))

You must use a delimiter like /

By the way, in order to validate an email address, you can use filter_var function as well.

$is_email_valid = filter_var($email, FILTER_VALIDATE_EMAIL);

Details: http://php.net/manual/en/function.filter-var.php

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top