How to get the domain name without www, subdomain, and com/net/org/etc
18,207
Solution 1
with the "PHP_URL_HOST" argument
then explode() on the "." and extract the penultimate element of the resulting array
Solution 2
Building off of Shyam's answer and employing the concept suggested by Mark Baker to get the penultimate element of the namespace, I might suggest using a simpler regular expression that utilizes an anchored lookahead like the following:
function get_domain($url) {
$matches = [];
preg_match('/[\w-]+(?=(?:\.\w{2,6}){1,2}(?:\/|$))/', $url, $matches);
return $matches[0];
}
Matches
-
names
inhttps://www.names.co.uk/
-
domain1
inhttp://www.subdomain.domain1.com/
-
domain2
inwww.subdomain.domain2.net
-
domain3
insubdomain.subdomain2.domain3.org/
-
domain4
inhttp://domain4.com
-
seventymm
inhttp://www.seventymm.co.in/browse/buy-home-furnishing-bed-sheets-pack-of-3/2456/1/v2034/0/0/1/2/1/0/go
Author by
user1502679
Updated on August 08, 2022Comments
-
user1502679 over 1 year
I just need to get the domain name only form a url, (without com and everything else) example:
I have:
http://www.subdomain.domain1.com/ www.subdomain.domain2.net subdomain.subdomain2.domain3.org/ http://domain4.com
I want to get with PHP:
domain1 domain2 domain3 domain4
-
user1502679 over 11 yearsBut how to get the penultimate element? so I can update the post with the solution. Thanks!
-
Decent Dabbler over 11 yearsBe aware of possible urls with top level domains such as
.co.uk
(are those officially called top level as well, by the way?), etc., though. -
Carlos over 11 years@fireeyedboy Very good point!
-
Syntax Error almost 9 yearsThis is not a flexible solution - it only works when the subdomain is known.
-
Wernight over 8 yearsIt'll also not work if you have only the IP.