开发者

Php regex string needs more delimiters?

I'm trying to use regex to check the validity of an email address in a php script. I use the following string as my regex

$reg = "\/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})\$\/";

I keep getting an error:

 Warning开发者_运维百科: preg_match(): Delimiter must not be alphanumeric or backslash

I've done my best to escape all special characters. is there something I'm missing?


You escape your delimiters, f.e:

$sCorrect = "/[a-z]/";
$sFalse = "\/[a-z]\/";

Even better, use:

filter_var($sVariable, FILTER_VALIDATE_EMAIL);


You escaped too many characters:

$reg = "/^([A-Za-z0-9_\-.])+@([A-Za-z0-9_\-.])+\.([A-Za-z]{2,4})$/";
  • The / regex delimiters (at the start and end of your regex) shouldn't be escaped
  • The metacharacters ^ and $ shouldn't be escaped.
  • The dot needs not to be escaped (but can be) when it's in a character class
  • The @ needs not to be escaped (but can be)

Regardless, creating your own regex to validate email addresses can be tricky. Most likely you are disallowing valid emails (eg: + is a valid character you are not allowing) and/or allowing invalid ones. The standards for this are set by RFC 822, I believe - and they are loooooooong.

Just use filter_var() as suggested by Wesley. Or better yet, send an email to the supplied address. That's the best and most reliable way to determine if the address is

a) valid
b) belongs to the user


An interesting read: I Knew How To Validate An Email Address Until I Read The RFC


$reg = "/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}\b/i"

Works with the new Gtld's

Explanation:

# Options: case insensitive
# 
# Assert position at a word boundary «\b»
# Match a single character present in the list below «[A-Z0-9._%+-]+»
#    Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
#    A character in the range between “A” and “Z” «A-Z»
#    A character in the range between “0” and “9” «0-9»
#    One of the characters “._%” «._%»
#    The character “+” «+»
#    The character “-” «-»
# Match the character “@” literally «@»
# Match a single character present in the list below «[A-Z0-9.-]+»
#    Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
#    A character in the range between “A” and “Z” «A-Z»
#    A character in the range between “0” and “9” «0-9»
#    The character “.” «.»
#    The character “-” «-»
# Match the character “.” literally «\.»
# Match a single character in the range between “A” and “Z” «[A-Z]{2,6}»
#    Between 2 and 6 times, as many times as possible, giving back as needed (greedy) «{2,6}»
# Assert position at a word boundary «\b»
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜