0

Currently, I can strip the domain of the URL string by:

$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];
}

This will echo:

example.com

The problem is that I want to include the subdomain if it exists.

So for example:

$url = 'http://sub.domain.example.com/foo/bar?hat=bowler&accessory=cane';

Should echo:

sub.domain.example.com

How can I achieve this insanity?

Henrik Petterson
  • 6,862
  • 20
  • 71
  • 155

1 Answers1

4

You can use the parse_url() function for this:

$str = 'http://sub.domain.example.com/foo/bar?hat=bowler&accessory=cane';
$parts = parse_url($str);
print_r($parts);

Output:

Array
(
    [scheme] => http
    [host] => sub.domain.example.com
    [path] => /foo/bar
    [query] => hat=bowler&accessory=cane
)

Thus:

echo $parts['host'];

Gives you:

sub.domain.example.com
Alex Howansky
  • 50,515
  • 8
  • 78
  • 98