Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get user name from an E-mail address in php

Tags:

string

php

email

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 @?

like image 388
Steve Martin Avatar asked Aug 14 '13 15:08

Steve Martin


People also ask

How can I check if an email address exists in PHP?

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.


2 Answers

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
}
like image 107
Ja͢ck Avatar answered Sep 26 '22 12:09

Ja͢ck


Try the following:

$string = "[email protected]";

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

array_pop($explode);

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

echo $newstring;

Modified for multiple '@' symbols.

like image 44
Ben Fortune Avatar answered Sep 22 '22 12:09

Ben Fortune