phpurlparse

How to isolate the domain name from a URL?


I'm looking for a method (or function) to strip out the example.ext part of any URL that's fed into the function. The domain extension can be anything (.com, .co.uk, .nl, .whatever), and the URL that's fed into it can be anything from http://www.example.com to www.example.com/path/script.php?=whatever

What's the best way to go about doing this?

I'd like example.com.


Solution

  • 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
    )