Search code examples
phpurlhtml-parsingurl-parsingurlparse

Get Host name from given URL


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.


Solution

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