如何获取电子邮件地址中@符号后面的部分

3

我正在尝试确定最佳方法来确定电子邮件地址是outlook还是hotmail地址。

因此,我需要收集@符号后的值。

例如:

testemail@outlook.com 

捕获 @ 符号

然而,这种方法不适用于所有情况,因为

此电子邮件地址有效:

"foo\@bar"@iana.org

我读到的解决方案是将其分解,即:
$string = "user@domain.com";

$explode = explode("@",$string);

array_pop($explode);

$newstring = join('@', $explode);

echo $newstring;

这个解决方案看起来有点冗长,而且只能捕获第一个值。希望能得到一些帮助。

你考虑过使用正则表达式吗? - belwood
@belwood 在这种情况下,我建议使用小锤子来解决问题。 - RiggsFolly
6个回答

0

如果你爆炸了这个:

$string = "user@domain.com";

$explode = explode("@",$string);

翻译后的文本为:

$explode[0] = user
$explode[1] = domain.com

0
尝试使用array_reverse()来获取电子邮件的最后一个值:
<?php
$email='exa@mple@hotmail.com';
$explode_email=explode('@',$email);
$reversed_array=array_reverse($explode_email);
$mailserver=explode('.',$reversed_array[0]);

echo $mailserver[0];
?>

0

你可以简单地使用strpos()或stripos()函数来测试字符串中是否存在任意一个值。

if ( FALSE !== stripos($string, 'outlook') {
    // outlook exists in the string
}

if ( FALSE !== stripos($string, 'hotmail') {
    // hotmail exists in the string
}

0
我建议使用正则表达式进行匹配。
if (preg_match("/\@hotmail.com$/", $email)) {
    echo "on hotmail";
} else if (preg_match("/\@outlook.com$/", $email)) {
    echo "on outlook";
} else {
    echo "different domain";
}

此外,如果您想将完整域名捕获到变量中,可以像这样操作:
$matches = [];
if (preg_match("/^.*\@([\w\.]+)$/", $email, $matches)) {
    echo "Domain: " . $matches[1];
} else {
    echo "not a valid email address.";
}

0

试试这个:

$emailAddress = 'example\@sometext\@someothertext@hotmail.com';

$explodedEmail = explode('@', $emailAddress);
$emailServerHostName = end($explodedEmail);
$emailServerNameExploded = explode('.', $emailServerHostName);
$emailServerName = $emailServerNameExploded[0];

echo $emailServerName;

0

我希望你能轻松理解这个。

<?php
$emailAddress = 'mailbox@hotmail.com'; //Email Address

$emailStringArray = explode('@',$emailAddress);  // take apart the email string.

$host = $emailStringArray[1];  //last string after @ . $emailStringArray[0] = Mailbox  & $emailStringArray[1] = host
if($host == "hotmail.com" || $host == "outlook.com"){
//matches to outlook.com or hotmail.com
}
else{
    //Does not match to outlook.com or hotmail.com
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接