简体   繁体   English

PHP切断从Outlook复制的电子邮件地址字符串

[英]PHP cuts off email address string copied from Outlook

I have a form which is used to send emails via PHP. 我有一个用于通过PHP发送电子邮件的表格。 Now I had a user who said the email didn't go through. 现在我有一个用户说电子邮件没有通过。 I checked, it appeared that only a name was saved in the field for the email address, not an email address. 我检查了一下,看来只有一个名称被保存在电子邮件地址的字段中,而不是电子邮件地址。

So I added a client-side validation via regex which only allows you to send if the email has the format [text]@[text].[text] - common practice for validating email addresses. 因此,我通过正则表达式添加了一个客户端验证,该验证仅在电子邮件具有[text] @ [text]。[text]格式的情况下才发送。

The used regex: 使用的正则表达式:

 var regex = /\S+@\S+\.\S+/;

Guess what? 你猜怎么了? The problem still occurs: user can send an email, the address passes the validation, but it only saves a name! 问题仍然存在:用户可以发送电子邮件,地址通过验证,但仅保存名称!

But how? 但是如何?

The user had copied the email address from Outlook, which comes in the following format: 用户已从Outlook复制了电子邮件地址,其格式如下:

Mustermann, Max <Max.Mustermann@gmail.com>

Regex validation says: that's a valid email address. 正则表达式验证说:这是一个有效的电子邮件地址。

At first I thought I had to change my regex, to not allow this. 起初,我以为我必须更改我的正则表达式,以不允许这样做。 But one of my co-workers says this is a valid format for email adresses. 但是我的一位同事说这是电子邮件地址的有效格式。

So I started looking into what PHP actually did with that string. 因此,我开始研究PHP实际上对该字符串做了什么。 And here it becomes strange: 在这里变得奇怪:

$email = "Mustermann, Max <Max.Mustermann@gmail.com>";
var_dump($email);
// prints out:
// string(42) "Mustermann, Max "

The string stops at the < , but its length is still 42. What exactly happens here? 字符串在<处停止,但长度仍为42。在这里究竟发生了什么?

Edit: 编辑:

End of the story: I'm using a stricter regex to validate the email adress now, namely the same which is used by the HTML5 input type="email" from W3C : 故事的结尾:我现在使用更严格的正则表达式来验证电子邮件地址,即W3CHTML5输入type =“ email”使用的相同:

/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/

PHP does not cut anything off. PHP不会切断任何东西。 but the < and > are interpreted as HTML-tags and therefore omitted by your browser. <>被解释为HTML标签,因此您的浏览器将其省略。 just look at the page source code and you will find your missing chars. 只需查看页面源代码,您就会找到丢失的字符。

to see the whole text in HTML, you have to escape it: 要查看HTML中的整个文本,您必须对其进行转义:

echo htmlentities($email);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM