假设电子邮件地址有效,则此文本方法应该有效:
$prefix = substr($email, 0, strrpos($email, '@'));
它需要一切(但不包括)最后一次出现的@
。它使用最后一次出现,因为此电子邮件地址有效:
"foo\@bar"@iana.org
如果你还没有验证字符串,我建议使用过滤函数:
if (($email = filter_var($email, FILTER_VALIDATE_EMAIL)) !== false) {
// okay, should be valid now
}
请尝试以下方法:
$string = "[email protected]";
$explode = explode("@",$string);
array_pop($explode);
$newstring = join('@', $explode);
echo $newstring;
修改为多个'@'符号。
您可以使用
$user = implode('@', explode('@', $email, -1));
要么
$user = substr($email, 0, strrpos($mail, '@'));
在strpos()
函数的PHP手册条目中有一个很好的例子:http://php.net/manual/en/function.strstr.php#117530
PHP让您轻松上手。使用电子邮件地址的域部分时,只需将strstr()的返回值传递给substr()并从1开始:
substr(strstr($haystack, '@'), 1);
在最简单的形式(假设单个'@'),您可以关注@Ben Fortune的答案(使用explode())。
否则,试试这个:
$email1 = "[email protected]";
$email2 = "b\@[email protected]";
preg_match_all ("/^(.+)@[^@]+$/", $email1, $e1);
preg_match_all ("/^(.+)@[^@]+$/", $email2, $e2);
echo "Emails: {$e1[1][0]} and {$e2[1][0]}\n";
// Result: Emails: foo and b\@r