Getting domain name without TLD

前端 未结 4 1088
轻奢々
轻奢々 2020-12-21 07:12

I have this code right here:

    // get host name from URL
    preg_match(\'@^(?:http://)?([^/]+)@i\',
    \"http://www.joomla.subdomain.php.net/index.html\"         


        
相关标签:
4条回答
  • 2020-12-21 07:16

    Late answer and it doesn't work with subdomains, but it does work with any tld (co.uk, com.de, etc):

    $domain = "somesite.co.uk";
    $domain_solo = explode(".", $domain)[0];
    print($domain_solo);
    

    Demo

    0 讨论(0)
  • 2020-12-21 07:18

    Group the first part of your 2nd regex into /([^.]+)\.[^.]+$/ and $matches[1] will be php

    0 讨论(0)
  • 2020-12-21 07:19

    It's really easy:

    function get_tld($domain) {
        $domain=str_replace("http://","",$domain); //remove http://
        $domain=str_replace("www","",$domain); //remowe www
        $nd=explode(".",$domain);
        $domain_name=$nd[0];
        $tld=str_replace($domain_name.".","",$domain);
        return $tld;
    }
    

    To get the domain name, simply return $domain_name, it works only with top level domain. In the case of subdomains you will get the subdomain name.

    0 讨论(0)
  • 2020-12-21 07:32

    Although regexes are fine here, I'd recommend parse_url

    $host = parse_url('http://www.joomla.subdomain.php.net/index.html', PHP_URL_HOST);
    $domains = explode('.', $host);
    echo $domains[count($domains)-2];
    

    This will work for TLD's like .com, .org, .net, etc. but not for .co.uk or .com.mx. You'd need some more logic (most likely an array of tld's) to parse those out .

    0 讨论(0)
提交回复
热议问题