0

I'm wanting to strip out everything from a URL but the domain. So https://i.stack.imgur.com/inhSc.jpg becomes imgur.com.

$url = 'https://i.stack.imgur.com/inhSc.jpg';

$parsedurl = parse_url($url);

$parsedurl = preg_replace('#^www\.(.+\.)#i', '$1', $parsedurl['host']);

// now if a dot exists, grab everything after it. This removes any potential subdomain
$parsedurl = preg_replace("/^(.*?)\.(.*)$/","$2",$parsedurl);

The above works but I feel like I should only being one preg_replace for this. Any idea how I may combine the two?

ditto
  • 5,917
  • 10
  • 51
  • 88
  • 1
    possible duplicate of [Get domain name (not subdomain) in php](http://stackoverflow.com/questions/2679618/get-domain-name-not-subdomain-in-php) – Federkun Sep 26 '15 at 11:41
  • http://stackoverflow.com/questions/16027102/get-domain-name-from-full-url – ka_lin Sep 26 '15 at 11:43

1 Answers1

0

You can use parse_url() to get desired output like this,

    $url = "http://i.imgur.com/rA81kQf.jpg";
    $parseData = parse_url($url);
    $domain = preg_replace('/^www\./', '', $parseData['host']);


    $array = explode(".", $domain);

    echo (array_key_exists(count($array) - 2, $array) ? $array[count($array) - 2] : "") . "." . $array[count($array) - 1];

which prints

imgur.com

Niranjan N Raju
  • 12,047
  • 4
  • 22
  • 41