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?

Edited by -Karl-
Link to comment
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);
?>

Link to comment
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);
?>

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

 

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

Link to comment
Share on other sites

Ended up doing an explode:

				 $parse = parse_url($image);
				 $url = $parse['host'];
				 $explode = explode('.',$url);
				 if(count($explode) > 2) {
					 $url = $explode[1].'.'.$explode[2];
				 }

 

Just need to do some testing for all possible variables now.

Edited by -Karl-
Link to comment
Share on other sites

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

Edited by ignace
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.