skip to Main Content

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


  1. 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.

    $parts = explode('.',$company);
    

    in your simple case you would have the domain (newsite) in $parts[0] and the top-level domain (com) in $parts[1]

    $domain = $parts[0];
    

    In general there are complications. Consider a subdomain within an email address such as

    [email protected]
    

    You might want to count the parts and choose the second last one as the domain, as in:

    $domain_index = count($parts) - 1 - 1; //since php index starts from 0 we have to take that into account
    $domain = $parts[$domain_index];
    

    Depending on your user profile you might also want to exclude certain email domains from providers like gmail, microsoft, apple, yahoo, etc.

    Login or Signup to reply.
  2. 2 solutions:

    1. use strpos for fisrt match of '@' and strrpos() for last match of '.', here’s a function:
    function companyName($email){
        $companyCom = substr($email, strpos($email, '@')+1); //get string after '@'
        $company = substr($companyCom,0,strrpos($companyCom,'.')); //get string before the last '.'
        return $company;
    }
    
    $emailWithDots= "[email protected]";
    $email= "[email protected]";
    echo companyName($emailWithDots); //company.uk.en
    echo companyName($email); //company.uk
    
    1. if you you don’t have [email protected], you can use explode() twice, here’s a function:
    function companyName($email){
        $company = explode('.',explode('@',$email)[1])[0];
        return $company; //company
    }
    
    $email="[email protected]";
    echo companyName($email); //company
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search