简体   繁体   English

在PHP中以字符串形式查找电子邮件地址

[英]Find an email address in a string in PHP

I wondered if anyone has any idea how to best do this in php. 我想知道是否有人知道如何最好地在php中做到这一点。

I have a string in a variable and I want to pull an email address from it (if one exists). 我在变量中有一个字符串,我想从中提取一个电子邮件地址(如果存在)。

The string could be along the lines of : 该字符串可能类似于:

"My email address is myemail@mydomain.com and I would appreciate it if you contact me" “我的电子邮件地址是myemail@mydomain.com,如果您与我联系,将不胜感激”

I know I can validate if an email is valid or not but wondered how to search a string and extract the email. 我知道我可以验证电子邮件是否有效,但想知道如何搜索字符串并提取电子邮件。

IE: I can use filters to validate the email but I am stuck at how to search the string to see if it has an email. IE:我可以使用过滤器来验证电子邮件,但是我仍然局限于如何搜索字符串以查看其是否包含电子邮件。

This should work fairly well. 这应该工作得很好。 You'll get things that appear to be an email address though they may not be valid. 您可能会看到似乎是电子邮件地址的内容,尽管它们可能无效。 Then use filter_var() to check if it's valid. 然后使用filter_var()检查它是否有效。

preg_match('/\b[^\s]+@[^\s]+/', $string, $match);
echo $match[0];

Match: 比赛:

  • A word boundary \\b followed by 单词边界 \\b后跟
  • NOT white space [^\\s]+ followed by NOT 空格 [^\\s]+后跟
  • A @ followed by A @后跟
  • NOT white space [^\\s]+ 空格 [^\\s]+

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

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