Reputation: 21
I need to get domain name from URL
domain.com
domain.co.uk
I should get:
.com
.co.uk
I tried with explode function but doesn't display domain ".co.uk"(example)
<?php
$url = "domain.com";
$host = explode('.', $url);
print $host[1];
?>
Upvotes: 1
Views: 639
Reputation: 3389
Yeah, use php function parse_url
(http://php.net/parse_url), it will help you.
Upvotes: 3
Reputation: 605
UPDATE based off (currently third answer) - Remove domain extension
$url = 'php.co.uk';
preg_match('/(.*?)((?:\.co)?.[a-z]{2,4})$/i', $url, $matches);
print_r($matches);
IGNORE FOLLOW - Bad practice, but still explains working of explode.
See when you explode and you use '.', it finds it twice in .co.uk. So if you where to echo both $host[1] & $host[2] you would get co uk respectively.
So as a partially complete (not sure what your end game is) solution:
Solution:
$url = "domain.co.uk";
$host = explode('.', $url);
$first = true;
foreach($host as $hostExtension){
if($first){
$first = !$first;
continue;
}
else{
echo $hostExtension .'<br>';
}
}
To be clear though, the other answers explain how you should be parsing the URL. I just merely thought to explain why (answering the question) your code was doing/return what it was and how you would get your intended result.
Upvotes: -2