电子邮件格式 REGEX PHP - 有很多类似的格式,但这是我的
呃,它坏了:
我有一个完美工作的正则表达式,它允许所有数字、字母和仅与电子邮件相关的标点符号 (._-@) 来清理我的电子邮件字段,然后我认为添加正确的电子邮件会很好正则表达式,检查正确的模式。这就是我现在所拥有的:
function check_chars_email($str) {
$str_replace = preg_replace("/[^a-zA-Z0-9-@_\.]/","",$str);
if(preg_match("/^(.*)@(.*)\.(.*)$/", $str_replace)) {
return $str_replace;
} else {
return FALSE;
}
我知道我不需要 .* 周围的括号,但发现它使它更清晰。
当我调用该函数时,它是这样的:
$esc_email = mysqli_real_escape_string($mysqli, check_chars_email($_POST["email"]));
$tr_email = trim($esc_email);
$_SESSION["email"] = $tr_email;
然后,除其他外,我在注册脚本开始时使用它来验证它:
($tr_email === FALSE)
尽管尝试使用有效的电子邮件地址,我失败了。我也在测试变量是否为空,所以我想我可以尝试 ==FALSE 而不是 ===,但我想尽可能精确。
有人有什么想法吗?
Uh, and it's broken:
I had a perfectly working regex that allowed all the numbers, letters and only e-mail relevant punctuation (._-@) to sanitize my email fields, and then I thought it would be nice adding a proper email regex, checking for the correct pattern. This is what I have now:
function check_chars_email($str) {
$str_replace = preg_replace("/[^a-zA-Z0-9-@_\.]/","",$str);
if(preg_match("/^(.*)@(.*)\.(.*)$/", $str_replace)) {
return $str_replace;
} else {
return FALSE;
}
I'm aware I don't need the brackets around the .* but find it makes it more legible.
When I call that function, it is like this:
$esc_email = mysqli_real_escape_string($mysqli, check_chars_email($_POST["email"]));
$tr_email = trim($esc_email);
$_SESSION["email"] = $tr_email;
And I then use, among other things, this to verify it at the start of my registration script:
($tr_email === FALSE)
And despite trying it with a valid e-mail address, I get a failure. I am also testing if the variable is empty, so I guess I could try ==FALSE instead of ===, but I want to be as precise as possible.
Anyone have any thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当 PHP 已经这样做时,为什么还要使用正则表达式呢?
请参阅
filter_var()
和 验证过滤器。Why would you use a regex for this when PHP already does it?
See
filter_var()
and validate filters.http://code.iamcal.com/php/rfc822/
http://code.google.com/p/isemail/source/browse/trunk /is_email.php
http://code.iamcal.com/php/rfc822/
http://code.google.com/p/isemail/source/browse/trunk/is_email.php