In PHP, I have a string like this:
$string = "user@domain.com";
How do I get the "user" from email address only? Is there any easy way to get the value before @
?
In PHP, I have a string like this:
$string = "user@domain.com";
How do I get the "user" from email address only? Is there any easy way to get the value before @
?
Assuming the email address is valid, this textual approach should work:
$prefix = substr($email, 0, strrpos($email, '@'));
It takes everything up to (but not including) the last occurrence of @
. It uses the last occurrence because this email address is valid:
"foo\@bar"@iana.org
If you haven't validated the string yet, I would advice using a filter function:
if (($email = filter_var($email, FILTER_VALIDATE_EMAIL)) !== false) {
// okay, should be valid now
}
Try the following:
$string = "user@domain.com";
$explode = explode("@",$string);
array_pop($explode);
$newstring = join('@', $explode);
echo $newstring;
Modified for multiple '@' symbols.
You can use
$user = implode('@', explode('@', $email, -1));
or
$user = substr($email, 0, strrpos($mail, '@'));
There’s a nice example in the PHP manual entry for the strpos()
function: http://php.net/manual/en/function.strstr.php#117530
PHP makes this easy for you. When working with domain portion of email addresses, simply pass the return of strstr() to substr() and start at 1:
substr(strstr($haystack, '@'), 1);
You can use:
strstr($email, '@', true);
In the simplest form (assuming single '@'), you can follow @Ben Fortune's answer (using explode()).
Otherwise, try this:
$email1 = "foo@example.com";
$email2 = "b\@r@example.com";
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