将电子邮件地址与给定的字符串格式分开

时间:2014-10-04 05:52:09

标签: php regex

我有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

5 个答案:

答案 0 :(得分:2)

如果您的文件位于文本文件中,并且每个文件都在一行中,那么您可以提取每一行并获取电子邮件....

$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);

答案 1 :(得分:1)

尝试explode()

$str = 'email1@yahoo.com,US,Wolterman,http://www.example.com/profile.php?id=12';
$res = explode(',', $str);
echo $res[0]; //email1@yahoo.com

答案 2 :(得分:1)

只需使用以下正则表达式

/.*?@.*?(?=,)/g

DEMO

或者另一种选择是在\n上拆分文本,然后在每一行上进行迭代,在,上拆分并捕获第一个元素。然而,当你可以将它与上面的正则表达式匹配时,这有点过分了。

答案 3 :(得分:1)

如果地址始终是第一个,那么这是一种可以做到这一点的方法。

$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

答案 4 :(得分:1)

有时候使用本地实现的东西也很好,比如fgetcsv

<?php
$emails = [];
if (($handle = fopen("emails.txt", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $emails[] = array_shift($data);
    }
    fclose($handle);
}
相关问题