How do you strip out the domain name from a URL in php?

后端 未结 9 1244
遥遥无期
遥遥无期 2020-12-02 22:12

Im looking for a method (or function) to strip out the domain.ext part of any URL thats fed into the function. The domain extension can be anything (.com, .co.uk, .nl, .what

相关标签:
9条回答
  • 2020-12-02 23:03

    Solved this...

    Say we're calling dev.mysite.com and we want to extract 'mysite.com'

    $requestedServerName = $_SERVER['SERVER_NAME']; // = dev.mysite.com
    
    $thisSite = explode('.', $requestedServerName); // site name now an array
    
    array_shift($thisSite); //chop off the first array entry eg 'dev'
    
    $thisSite = join('.', $thisSite); //join it back together with dots ;)
    
    echo $thisSite; //outputs 'mysite.com'
    

    Works with mysite.co.uk too so should work everywhere :)

    0 讨论(0)
  • 2020-12-02 23:03

    Following code will trim protocol, domain and port from absolute URL:

    $urlWithoutDomain = preg_replace('#^.+://[^/]+#', '', $url);
    
    0 讨论(0)
  • 2020-12-02 23:13

    parse_url turns a URL into an associative array:

    php > $foo = "http://www.example.com/foo/bar?hat=bowler&accessory=cane";
    php > $blah = parse_url($foo);
    php > print_r($blah);
    Array
    (
        [scheme] => http
        [host] => www.example.com
        [path] => /foo/bar
        [query] => hat=bowler&accessory=cane
    )
    
    0 讨论(0)
提交回复
热议问题