[英]Separate email address from given string format
I have the following type of data in txt format and there are hundreds of lines as below. 我有txt格式的以下数据类型,并且有几百行,如下所示。 How to only fetch emails from them.
如何仅从中获取电子邮件。
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
If your file is in text file and, each is in one line then you could extract each line and get email.... 如果您的文件位于文本文件中,并且每一行都在一行中,则可以提取每一行并获取电子邮件。
$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);
try explode()
尝试
explode()
$str = 'email1@yahoo.com,US,Wolterman,http://www.example.com/profile.php?id=12';
$res = explode(',', $str);
echo $res[0]; //email1@yahoo.com
Just use the below regex 只需使用下面的正则表达式
/.*?@.*?(?=,)/g
Or another option would be to split the text on \\n
and then iterating on each line, split on ,
and capture the first element. 另一个选择是在
\\n
上分割文本,然后在每一行上迭代,在上分割,
并捕获第一个元素。 This however is a bit over kill, when you can match it wasily with the above regex. 但是,当您可以将它与上面的正则表达式进行匹配时,这有点过头了。
Here is one way you could do this if the addresses are always first. 如果地址始终是第一位,这是一种可以执行此操作的方法。
$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]);
Output 输出量
email1@yahoo.com
email2@yahoo.com
email3@yahoo.com
email4@yahoo.com
email5@yahoo.com
email6@yahoo.com
It can also be nice sometimes to use native implementations of things, like fgetcsv : 有时使用诸如fgetcsv之类的事物的本机实现也可能很好:
<?php
$emails = [];
if (($handle = fopen("emails.txt", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$emails[] = array_shift($data);
}
fclose($handle);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.