我有以下类型的txt格式的数据,下面有数百行。如何只从他们那里获取电子邮件。
email1@yahoo.com,US,Wolterman,http://www.example.com/profile.php?id=12
email2@yahoo.com,UK,superman,http://www.example.com/profile.php?id=21
如果你的文件在文本文件中,并且每一行都在一行中,那么你可以提取每一行并获得电子邮件。。。。
$array = array(); // Array where emails are stored
$handle = fopen("textfile.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$array[] = explode(",",$line)[0]; // stores email in the array
}
} else {
// error opening the file.
}
fclose($handle);
print_r($array);
如果地址总是第一位,这里有一种方法可以做到这一点。
$text = <<<DATA
email1@yahoo.com,US,Wolterman,http://www.example.com/profile.php?id=12
email2@yahoo.com,UK,superman,http://www.example.com/profile.php?id=21
email3@yahoo.com,US,Wolterman,http://www.example.com/profile.php?id=12
email4@yahoo.com,UK,superman,http://www.example.com/profile.php?id=21
email5@yahoo.com,US,Wolterman,http://www.example.com/profile.php?id=12
email6@yahoo.com,UK,superman,http://www.example.com/profile.php?id=21
DATA;
preg_match_all('~^[^,]+~m', $text, $matches);
echo implode("'n", $matches[0]);
输出
email1@yahoo.com
email2@yahoo.com
email3@yahoo.com
email4@yahoo.com
email5@yahoo.com
email6@yahoo.com
尝试explode()
$str = 'email1@yahoo.com,US,Wolterman,http://www.example.com/profile.php?id=12';
$res = explode(',', $str);
echo $res[0]; //email1@yahoo.com
只需使用以下regex
/.*?@.*?(?=,)/g
演示
或者另一种选择是在'n
上拆分文本,然后在每一行上迭代,在,
上拆分并捕获第一个元素。然而,当您可以将它与上面的regex进行wasily匹配时,这就有点过分了。
有时使用事物的本机实现也很好,比如fgetcsv:
<?php
$emails = [];
if (($handle = fopen("emails.txt", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$emails[] = array_shift($data);
}
fclose($handle);
}