Using regex to extract username from email address

Viewed 60764

My string of text looks like this:

johndoe@domain.com (John Doe)

I need to get just the part before the @ and nothing else. The text is coming from a simple XML object if that matters any.

The code I have looks like this:

$authorpre = $key->{"author"};
$re1 = '((?:[a-z][a-z]+))';

if ($c = preg_match_all ("/".$re1."/is", $authorpre, $matches))
{
    $author = $matches[1][0];
}

Sometimes the username might have numbers or an underscore before the @ symbol, which is where the regex stops it seems.

12 Answers

I used preg_replace

$email_username = preg_replace('/@.*/', '', $_POST['email']);

In case someone is still looking in 2020 ..here's the regex that can pick the text before the '@'

^(\S+)(?=@)

I would also like to suggest a non regex solution here as it may be useful in most cases:

strstr('n.shah@xyz.co', '@', true)

output:

n.shah

Related