我有一个文本块,我想从中提取有效的电子邮件地址并将它们放入一个数组中。到目前为止我已经...
$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 [email protected] /cdn-cgi/l/email-protection, 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]);
output:
array (
0 => '[email protected] /cdn-cgi/l/email-protection',
1 => '[email protected] /cdn-cgi/l/email-protection',
2 => '[email protected] /cdn-cgi/l/email-protection',
3 => '[email protected] /cdn-cgi/l/email-protection',
4 => '[email protected] /cdn-cgi/l/email-protection',
)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)