If $domain = apple.com, or mit.org.edu.au, how can I remove the '.com' and everything starting from the dot using PHP? e.g. apple.com becomes apple, mit.org.edu.au becomes mit (disregard www.).
-
3What have you tried? See the FAQ, please.John Conde– John Conde2013-01-04 03:28:35 +00:00Commented Jan 4, 2013 at 3:28
-
can this happen?? @JohnCondemamdouh alramadan– mamdouh alramadan2013-01-04 03:31:42 +00:00Commented Jan 4, 2013 at 3:31
-
@PranavKapoor Not quite, OP is asking for the first token, dup is asking for everything but the last.hafichuk– hafichuk2013-01-04 03:38:19 +00:00Commented Jan 4, 2013 at 3:38
6 Answers
If you already have the domain then simply explode the domain and take the first element of the array.
$domain = 'apple.com';
$domain_parts = explode('.', $domain);
echo $domain_parts[0]; // returns apple
Note that the above will not account for subdomains. I.e. 'www.apple.com' would return 'www'. But based on what you have asked above, explode may be adequate.
If you don't already have the domain then you can use PHP's parse_url function to extract the domain (host) from the URL.
Comments
Like others said, use explode. $raw = 'apple.com'; $url = explode('.',$raw); echo $url[0];
If there is a "www" in the domain, then do a simple check like if($url[0] == 'www'){ echo $url[1]; }else{ echo $url[0]; }
I dislike all of these answers... if you KNOW the domain, none of this is necessary... if you DONT KNOW the domain, you most certainly should account for subdomains.
$parts = explode('.', $domain);
array_pop($parts); //remove the TLD
$url = join('.', $parts); //put it back together, sans the TLD