1

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];
?>
mrtest
  • 21
  • 2

2 Answers2

3

Yeah, use php function parse_url (http://php.net/parse_url), it will help you.

Eduardo Escobar
  • 3,301
  • 2
  • 18
  • 15
-2

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.

Community
  • 1
  • 1
Anees Saban
  • 607
  • 6
  • 11
  • terrible idea. use the built in functions not explode –  Dec 26 '15 at 22:36
  • I agree, but I thought to explain why he wasn't getting his intended result. – Anees Saban Dec 26 '15 at 22:38
  • @Dagon, Have you any idea for this, i would be grateful. – mrtest Dec 26 '15 at 23:02
  • See the thing is, usually I'd have recommended. pathinfo or parse_url, but according to those .uk is the extension and .co belongs to the domain name. – Anees Saban Dec 26 '15 at 23:07
  • @mrtest did you try parse_url () ? –  Dec 26 '15 at 23:08
  • http://stackoverflow.com/questions/3853338/remove-domain-extension/3853473#3853473 - currently third answer is the only working example I found. – Anees Saban Dec 26 '15 at 23:15
  • @Valdorous, thanks for ur answer, but i guess this thing can solve and with preg_replace but this function confuse me ! – mrtest Dec 26 '15 at 23:20
  • I edited the answer to add a working example for you. What it does is it creates an array. The first in the array is the full URL, the second is the domain half and the third is the extension (regardless of .'s). http://php.net/manual/en/function.preg-replace.php – Anees Saban Dec 26 '15 at 23:24