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

Viewed 64371

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, .whatever), and the URL thats fed into it can be anything from http://www.domain.com to www.domain.com/path/script.php?=whatever

Whats the best way to go about doing this?

9 Answers

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
)

You can use parse_url() to do this:

$url = 'http://www.example.com';
$domain = parse_url($url, PHP_URL_HOST);
$domain = str_replace('www.','',$domain);

In this example, $domain should contain example.com, irrespective of it having www or not. It also works for a domain such as .co.uk

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.

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

$urlWithoutDomain = preg_replace('#^.+://[^/]+#', '', $url);

This function should work:

function Delete_Domain_From_Url($Url = false)
{
    if($Url)
    {
        $Url_Parts = parse_url($Url);
        $Url = isset($Url_Parts['path']) ? $Url_Parts['path'] : '';
        $Url .= isset($Url_Parts['query']) ? "?".$Url_Parts['query'] : '';
    }

    return $Url;
}

To use it:

$Url = "https://stackoverflow.com/questions/176284/how-do-you-strip-out-the-domain-name-from-a-url-in-php";
echo Delete_Domain_From_Url($Url);

# Output: 
#/questions/176284/how-do-you-strip-out-the-domain-name-from-a-url-in-php
Related