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
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();
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.
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' ?>
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With