我正在尝试使用正则表达式来检查php脚本中电子邮件地址的有效性。我使用以下字符串作为我的正则表达式
$reg = "\/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})\$\/";
我一直收到错误:
Warning: preg_match(): Delimiter must not be alphanumeric or backslash
我尽力逃脱所有特殊角色。有什么我想念的吗?
答案 0 :(得分:9)
你逃脱了分界符,f.e:
$sCorrect = "/[a-z]/";
$sFalse = "\/[a-z]\/";
更好的是,使用:
filter_var($sVariable, FILTER_VALIDATE_EMAIL);
答案 1 :(得分:4)
你逃脱了太多字符:
$reg = "/^([A-Za-z0-9_\-.])+@([A-Za-z0-9_\-.])+\.([A-Za-z]{2,4})$/";
/
正则表达式分隔符(在你的正则表达式的开头和结尾)不应该被转义^
和$
。@
不需要转义(但可以)无论如何,创建自己的正则表达式以验证电子邮件地址可能会非常棘手。很可能您不允许有效的电子邮件(例如:+
是您不允许的有效字符)和/或允许无效的电子邮件。我相信这个标准是由RFC 822设定的 - 而且它们是loooooooong。
按照Wesley的建议使用filter_var()
。或者更好的是,发送电子邮件到提供的地址。这是确定地址是否
a)有效
b)属于用户
有趣的读物:I Knew How To Validate An Email Address Until I Read The RFC
答案 2 :(得分:-1)
$reg = "/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}\b/i"
说明:
# 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»