Jump to content

Extracting Root Domain


-Karl-

Recommended Posts

Hello,

 

I'm having difficulty extracting the root domain from an URL, whilst excluding a subdomain if one is there.

 

Basically:

 

				 $txt = 'http://i.imgur.com';
				 $parse = parse_url($txt);
				 $url = $parse['host'];

 

Returns i.imgur.com, but I only need imgur.com. However, the reason it's complicated is because the url could also be www.imgur.com, so you can't simply explode by ".", then there's also the problem with other tld's.

 

For example, m465.imageshack.us, all I need it to return is imageshack.us.

 

What would be the best way to achieve this?

Link to comment
https://forums.phpfreaks.com/topic/269772-extracting-root-domain/
Share on other sites

I think the best possible solution is the use of built in PHP function parse_url.

You can extract the domain name and might get the exact domain name by the help of string manipulator functions susch as substr() and strpos()

 

 

<?php
$url = parse_url("http://123.456.imageshack.us/image.png");
print_r($url);
?>

I think the best possible solution is the use of built in PHP function parse_url.

You can extract the domain name and might get the exact domain name by the help of string manipulator functions susch as substr() and strpos()

 

 

<?php
$url = parse_url("http://123.456.imageshack.us/image.png");
print_r($url);
?>

If you read my first post, parse_url() is exactly what I am using...

 

I then explained the reason why it's not suffice.

Based off Psycho's solution. You can pass a PHP_URL_HOST constant to parse_url also you can pass a negative value as offset to array_slice.

 

$image = 'http://123.456.imageshack.us/image.png';
$domain = implode('.', array_slice(explode('.', parse_url($image, PHP_URL_HOST)), -2)); // imageshack.us

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.