Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get domain name from full URL

Tags:

url

php

say someone enters a URL like this:

http://i.imgur.com/a/b/c?query=value&query2=value 

And I want to return: imgur.com

not i.imgur.com

This is code I have right now

$sourceUrl = parse_url($url); $sourceUrl = $sourceUrl['host']; 

But this returns i.imgur.com

like image 402
ramo Avatar asked Apr 16 '13 01:04

ramo


People also ask

How do I find the domain of a string?

Firstly, we'd need to extract the host from the given URL value. We can use the URI class: String urlString = "https://www.baeldung.com/java-tutorial"; URI uri = new URI(urlString); String host = uri. getHost();

How do I get the current domain in HTML?

window.location.href returns the href (URL) of the current page. window.location.hostname returns the domain name of the web host. window.location.pathname returns the path and filename of the current page.


2 Answers

Check the code below, it should do the job fine.

<?php  function get_domain($url) {   $pieces = parse_url($url);   $domain = isset($pieces['host']) ? $pieces['host'] : $pieces['path'];   if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {     return $regs['domain'];   }   return false; }  print get_domain("http://mail.somedomain.co.uk"); // outputs 'somedomain.co.uk'  ?> 
like image 157
stanev01 Avatar answered Sep 30 '22 01:09

stanev01


You need package that using Public Suffix List. Yes, you can use string functions arround parse_url() or regex, but they will produce incorrect result in complex URLs.

I recomend TLDExtract for domain parsing, here is sample code:

$url = 'http://i.imgur.com/a/b/c?query=value&query2=value';  parse_url($url, PHP_URL_HOST); // will return 'i.imgur.com'  $extract = new LayerShifter\TLDExtract\Extract(); $result = $extract->parse($url); $result->getFullHost(); // will return 'i.imgur.com' $result->getSubdomain(); // will return 'i' $result->getRegistrableDomain(); // will return 'imgur.com' $result->getSuffix(); // will return 'com' 
like image 26
Oleksandr Fediashov Avatar answered Sep 30 '22 01:09

Oleksandr Fediashov