Extract domain from email address

It's not as easy as it seems.

If you take a look at all of the allowable characters for the local part of an email address, the commercial at sign (@) is one of them. That means that an email address like:

first@last@example.com 

is a valid email address. If you do the standard explode, you'll get three parts, not two. A typical function would return:
first  as the local part
last  as the domain
and drop the real domain completely.

I wrote this function to extract the domain name even if the email address contains multiple @ signs.

// function to extract the domain name from an email address// @param string $email properly structured email address// @author Andy Prevost // @return string|boolean string: domain if valid; false if not real emailfunction getDomainFromEmail($email){return (str_contains($email, '@')) ? ltrim(strrchr($email, "@"),'@') : false;}

The syntax is simple:

$email = 'foo@bar@co.example.com';$domain = getDomainFromEmail($email);print_r($domain);
1 Comment

Did some research after reaching this tutorial. I am amazed the number of unusual characters allowed in the name of the email address. Even spaces. Thank you for the function. It's now part of my must-have utilities.
 ~ undisclosed – 2025-07-10
Add a comment