I have users registering on a site with their email address, example [email protected], I want to extract the company name “newsite” from the email address. I can get the email address down to newsite.com but I cant seem to pull out just the company name “newsite”.
Current Code:
$company = substr($email, strpos($email, '@') + 1); // if email address was [email protected] then it returns newsite.com
I just want “newsite”
2
Answers
You can use explode to split a string.
Once you have split the string at the @ either as you have done using
substr()
or usingexplode()
you can further subdivide the address.in your simple case you would have the domain (newsite) in
$parts[0]
and the top-level domain (com) in$parts[1]
In general there are complications. Consider a subdomain within an email address such as
You might want to count the parts and choose the second last one as the domain, as in:
Depending on your user profile you might also want to exclude certain email domains from providers like gmail, microsoft, apple, yahoo, etc.
2 solutions:
strpos
for fisrt match of'@'
andstrrpos()
for last match of'.'
, here’s a function:[email protected]
, you can useexplode()
twice, here’s a function: