我有一个文本块,我想从中提取有效的电子邮件地址并将它们放入一个数组中.到目前为止我有......
$string = file_get_contents("example.txt"); // Load text file contents
$matches = array(); //create array
$pattern = '/[A-Za-z0-9_-]+@[A-Za-z0-9_-]+\.([A-Za-z0-9_-][A-Za-z0-9_]+)/'; //regex for pattern of e-mail address
preg_match($pattern, $string, $matches); //find matching pattern
Run Code Online (Sandbox Code Playgroud)
但是,我得到一个只有一个地址的数组.因此,我猜我需要以某种方式循环这个过程.我怎么做?
Cla*_*son 28
你非常接近,但正则表达式不会捕获所有的电子邮件格式,你不需要指定A-Za-z,你可以使用"i"标志将整个表达式标记为不区分大小写.有错过的电子邮件格式案例(特别是子域名),但这会抓住我测试的那些.
$string = file_get_contents("example.txt"); // Load text file contents
// don't need to preassign $matches, it's created dynamically
// this regex handles more email address formats like a+b@google.com.sg, and the i makes it case insensitive
$pattern = '/[a-z0-9_\-\+]+@[a-z0-9\-]+\.([a-z]{2,3})(?:\.[a-z]{2})?/i';
// preg_match_all returns an associative array
preg_match_all($pattern, $string, $matches);
// the data you want is in $matches[0], dump it with var_export() to see it
var_export($matches[0]);
Run Code Online (Sandbox Code Playgroud)
输出:
array (
0 => 'test1+2@gmail.com',
1 => 'test-2@yahoo.co.jp',
2 => 'test@test.com',
3 => 'test@test.co.uk',
4 => 'test@google.com.sg',
)
Run Code Online (Sandbox Code Playgroud)
Eri*_*arl 19
我知道这不是你问的问题,但我注意到你的正则表达式不接受任何地址,如' myemail@office21.company.com'或任何带有子域的地址.您可以用以下内容替换它:
/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}/
Run Code Online (Sandbox Code Playgroud)
这将拒绝不太有效的电子邮件(尽管它并不完美).
我还建议你阅读这篇关于电子邮件验证的文章,它非常好,内容丰富.
ste*_*esu 11
您的代码几乎是完美的,你只需要更换preg_match(...)与preg_match_all(...)
http://www.php.net/manual/en/function.preg-match.php
http://www.php.net/manual/en/function.preg-match-all.php
这会检测所有邮件地址:
$sourceeee= 'Here are examplr mymail@yahoo.com and my-e.mail@goog.com or something more';
preg_match_all('/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}/i', $sourceeee, $found_mails);
Run Code Online (Sandbox Code Playgroud)
然后你可以使用$found_mails[0]数组.
| 归档时间: |
|
| 查看次数: |
29269 次 |
| 最近记录: |