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

后端 未结 9 1409
遥遥无期
遥遥无期 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 22:48

    You can also write a regular expression to get exactly what you want.

    Here is my attempt at it:

    $pattern = '/\w+\..{2,3}(?:\..{2,3})?(?:$|(?=\/))/i';
    $url = 'http://www.example.com/foo/bar?hat=bowler&accessory=cane';
    if (preg_match($pattern, $url, $matches) === 1) {
        echo $matches[0];
    }
    

    The output is:

    example.com
    

    This pattern also takes into consideration domains such as 'example.com.au'.

    Note: I have not consulted the relevant RFC.

提交回复
热议问题