In PHP, I have a string like this:
$string = "[email protected]";
How do I get the "user" from email address only? Is there any easy way to get the value before @
?
Validate email in PHP can be easily done by using filter_var() function with FILTER_VALIDATE_EMAIL filter. It will check if the format of the given email address is valid.
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 = "[email protected]";
$explode = explode("@",$string);
array_pop($explode);
$newstring = join('@', $explode);
echo $newstring;
Modified for multiple '@' symbols.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With