Skip to content

Instantly share code, notes, and snippets.

@c4pone
Created October 21, 2015 01:13
Show Gist options
  • Save c4pone/7f0f1f2de5786571654b to your computer and use it in GitHub Desktop.
Save c4pone/7f0f1f2de5786571654b to your computer and use it in GitHub Desktop.
Extracts the host from a given url
<?php
/**
* Extracts the host from the given url>
*
* Example:
* http://codebuster.de/ = codebuster.de
* http://codebuster.de/test = codebuster.de
*
* @param string $url
*
* @return string
*/
function extractHostFromUrl($value)
{
if (empty ($value)) {
throw new Exception('value is empty');
}
$parser = new \webignition\Url\Url($value);
if ($parser->getHost() === null) {
$parser->setScheme('http');
$parser->setHost($value);
}
$parser->setPath('');
if ( ! $parser->hasHost())
throw new Exception('no host detected');
$host = (string) $parser->getHost();
if (strpos($host, '.') === false)
throw new Exception('no tld detected');
$host = preg_replace('/^www\./','', $host);
$host = strtolower($host);
return $host;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment