2017-08-01 37 views
0

如果我有:正则表达式 - 在链接电子邮件的逗号处停留?

[email protected][email protected]

我只希望第一个电子邮件地址,我用:

'/([^\s][email protected][^\s]+)/s' 

但如果提供的数据没有像这样的空间:

me @ myemail.com,you @ youremail.com

我的表达式给出了整个字符串。如何在两个示例中获得第一个电子邮件地址?我的小提琴:https://regex101.com/r/rJ6b9n/1

+0

模式不是很好。即使你有空间,它将匹配逗号... – marekful

+0

有多尴尬 - 我没有注意到! – Warren

回答

0

使用^表明,模式开头:

^(([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.-_]+))

这只会采取的第一个邮件。

如果删除^它会选择每个邮件是入串

0

您可以添加逗号,它会找到第一个([^ \ s] + @ [^ \ S] +),

看到regex它会找到你的集团邮箱1

0

因为你的正则表达式是一个捕获组,你可以做这样的:

([^ \ s] + @ [^\ S] +)\,

0

我看到两种方式来完成这项工作:

$emails = array(
    '[email protected], [email protected]', 
    '[email protected],[email protected]', 
); 

// first approch, preg_match 
// find email followed by a comma 
foreach($emails as $email) { 
    preg_match('/\[email protected]\S+?(?=,)/', $email, $matches); 
    print_r($matches); 
} 
echo "=======================================================\n"; 

// second approch, preg_split 
foreach($emails as $email) { 
    echo preg_split('/,/', $email)[0],"\n"; 
} 

输出:

Array 
(
    [0] => [email protected] 
) 
Array 
(
    [0] => [email protected] 
) 
======================================================= 
[email protected] 
[email protected]