Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Get the domain name from a URL for display purposes in PHP
// This is PHP function to convert a user-supplied URL to just the domain name,
// which I use as the link text.
// Remember you still need to use htmlspecialchars() or similar to escape the
// result.
function url_to_domain($url)
$host = @parse_url($url, PHP_URL_HOST);
// If the URL can't be parsed, use the original URL
// Change to "return false" if you don't want that
if (!$host)
$host = $url;
// The "www." prefix isn't really needed if you're just using
// this to display the domain to the user
if (substr($host, 0, 4) == "www.")
$host = substr($host, 4);
// You might also want to limit the length if screen space is limited
if (strlen($host) > 50)
$host = substr($host, 0, 47) . '...';
return $host;
$url = '';
<a href="<?= htmlspecialchars($url) ?>">
<?= htmlspecialchars(url_to_domain($url)) ?>
<a href=""></a>

This comment has been minimized.

Copy link

jastisriradheshyam commented Jan 24, 2018

What about ww2,www2 ..... Subdomains.How to resolve with those subdomains


This comment has been minimized.

Copy link

abraovic commented Jan 30, 2018


@line 16 you might add $host = explode('/', $url)[0]; which will make it usable when url does not contain http(s) part. parse_url can not parse url if it does not contain http(s). In that case you can only get path which is basically url.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.