gpt4 book ai didi

php - 在 PHP 中,如何从文本 block 中提取多个电子邮件地址并将它们放入数组中?

转载 作者:IT王子 更新时间:2023-10-29 01:20:47 24 4
gpt4 key购买 nike

我有一个文本 block ,我想从中提取有效的电子邮件地址并将它们放入一个数组中。到目前为止,我...

   $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

但是,我得到一个只有一个地址的数组。因此,我猜我需要以某种方式循环这个过程。我该怎么做?

最佳答案

你很接近,但正则表达式不会捕获所有电子邮件格式,你不需要指定 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]);

输出:

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',
)

关于php - 在 PHP 中,如何从文本 block 中提取多个电子邮件地址并将它们放入数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3901070/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com