PHP error using the preg_match function [duplicate]

亡梦爱人 提交于 2019-12-24 13:07:14

问题


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.


回答1:


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




回答2:


You need to delimit your regular expression:

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



回答3:


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.




回答4:


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 /




回答5:


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



来源:https://stackoverflow.com/questions/19114821/php-error-using-the-preg-match-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!