我正在尝试使用regex来检查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
我已经尽了最大努力逃离所有特殊的角色。我缺什么了吗?
您可以转义分隔符,例如:
$sCorrect = "/[a-z]/";
$sFalse = "'/[a-z]'/";
更好的是,使用:
filter_var($sVariable, FILTER_VALIDATE_EMAIL);
您转义了太多字符:
$reg = "/^([A-Za-z0-9_'-.])+@([A-Za-z0-9_'-.])+'.([A-Za-z]{2,4})$/";
/
正则表达式分隔符(位于正则表达式的开头和末尾(不应转义- 不应转义元字符
^
和$
- 点在字符类中时不需要转义(但可以转义(
@
不需要转义(但可以转义(
无论如何,创建自己的正则表达式来验证电子邮件地址可能很棘手。很可能你不允许有效的电子邮件(例如:+
是你不允许的有效字符(和/或允许无效的电子邮件。我相信,这方面的标准是由RFC 822制定的,而且它们太棒了。
按照卫斯理的建议使用filter_var()
即可。或者更好的是,发送一封电子邮件到提供的地址。这是确定地址是否为的最佳和最可靠的方法
a( 有效
b( 属于用户
有趣的阅读:在阅读RFC 之前,我知道如何验证电子邮件地址
$reg = "/'b[A-Z0-9._%+-]+@[A-Z0-9.-]+'.[A-Z]{2,6}'b/i"
与新Gtld的配合使用
说明:
# 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»