Preg 允许空白记录

我有以下代码用于使用正则表达式规则匹配电子邮件地址。


它运作良好,但我最近注意到它似乎与“空白”电子邮件地址匹配。


if (preg_match("/.* <.*@.*\..*>/i",$this->to,$matches)) {

  $this->email_to = preg_replace("/.*<(.*)>.*/","$1",$this->to);

} else {

  $this->email_to = $this->to;

}

我对 preg_match 的理解是:-

  1. 查找任何字符,除了换行符

  2. <任何字符@anything.anything >

  3. 不区分大小写?

按照这些规则,如果有人可以提供一些指导,我无法完全弄清楚为什么它与空白/没有电子邮件地址匹配。

谢谢你。


繁花如伊
浏览 152回答 2
2回答

守着星空守着你

不需要preg_match + preg_replace。if (empty($this->to)) {&nbsp; &nbsp; $this->email_to = 'Is empty'; # assign what you want} elseif (preg_match("/<(.+?@.+?\..+?)>/", $this->to, $matches)) {&nbsp; &nbsp; $this->email_to = $matches[1];} else {&nbsp; &nbsp; $this->email_to = $this->to;}

子衿沉夜

我不知道它为什么会这样,但一个简单的解决方案是询问字符串是否为空白if (preg_match("/.* <.*@.*\..*>/i",$this->to,$matches)) {&nbsp; if ($matches != ""){&nbsp; &nbsp; &nbsp; $this->email_to = preg_replace("/.*<(.*)>.*/","$1",$this->to);&nbsp; &nbsp; &nbsp; } else { $this->email_to = $this->to; }} else {&nbsp; $this->email_to = $this->to;}
打开App,查看更多内容
随时随地看视频慕课网APP