1

how to get host name from bellow Example.

I/P: https://stackoverflow.com/users/login | O/P: stackoverflow.com

I/P: stackoverflow.com/users/login | O/P: stackoverflow.com

I/P: /users/login | O/P: (return empty string)

I checked parse_url function, but doesn't return what I need. Since, I'm beginner in PHP, it was difficult for me. If you have any idea, please answer.

BrennQuin
  • 656
  • 10
  • 19
San Ka Ran
  • 156
  • 2
  • 18

4 Answers4

2

This should work in all kind of domain name

$url = " https://stackoverflow.com/users/login";
// trailing slash for edge case, it will return empty string for strstr function regardless
$test = str_replace(array("http://", "https://"), "", $url) . "/";
$domain = strstr($test, "/", true);
echo $domain; // stackoverflow.com

$domain will be an empty string if no domain found

Andrew
  • 2,810
  • 4
  • 18
  • 32
1

You can try this -

$url = ' https://stackoverflow.com/users/login';

function return_host($url)
{
  $url = str_replace(array('http://', 'https://'), '', $url); // remove protocol if present
  $temp = explode('/', $url); // explode the url by /
  if(strpos($temp[0], '.com')) { // check the url part
     return $temp[0];
  }
  else {
     return false;
  }
}

echo return_host($url);

Update

For other domain types just change the check -

if(strpos($temp[0], '.com') || strpos($temp[0], '.org') || strpos($temp[0], '.net'))

DEMO

Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
1

you can try this

<?php  

function getHost($Address) { 
   $parseUrl = parse_url(trim($Address)); 
   return trim(isset($parseUrl['host']) ? $parseUrl['host'] : array_shift(explode('/', $parseUrl['path'], 2))); 
} 

echo getHost('http://stackoverflow.com/users/login');
Jah
  • 986
  • 5
  • 26
0

You can use regular expressions, as described in this solution: Getting parts of a URL (Regex)

Or you can use a PHP function for that: http://php.net/manual/en/function.parse-url.php

I would suggest the second (RegExes can be tricky if you don't know exactly how they work).

Community
  • 1
  • 1
Dmitri Sologoubenko
  • 2,909
  • 1
  • 23
  • 27