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.
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');
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'))
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).
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