Skip to content

Instantly share code, notes, and snippets.

@RobinDev
Last active August 29, 2015 14:07
Show Gist options
  • Save RobinDev/f0d18850b5d21088123e to your computer and use it in GitHub Desktop.
Save RobinDev/f0d18850b5d21088123e to your computer and use it in GitHub Desktop.
PHP function : Get domain (Host to be exact) from any string (with or without pares_url)
<?php
/**
* Return (sub)domain from any string (with and without parse_url)
*
* @param $domain str
*/
function getDomain($domain) {
$host = parse_url($domain, PHP_URL_HOST);
if($host)
return $host;
$domain = preg_replace('#[a-z]+://#siU', '', $domain);
$domain = preg_replace('#(/.*)$#siU', '', $domain);
return $domain;
}
header("Content-Type:text/plain;charset=utf-8");
$domains = explode(chr(10), 'http://example.com
https://example.com
http://example.com/foo
http://example.com/foo/bar
www.example.com
example.com
foo.example.com
www.foo.example.com
foo.bar.example.com
http://foo.bar.example.com/foo/bar
example.net/foo/bar');
foreach($domains as $domain) {
echo $domain.' '.getDomain($domain).chr(10);
}
/**
* Return
http://example.com example.com
https://example.com example.com
http://example.com/foo example.com
http://example.com/foo/bar example.com
www.example.com www.example.com
example.com example.com
foo.example.com foo.example.com
www.foo.example.com www.foo.example.com
foo.bar.example.com foo.bar.example.com
http://foo.bar.example.com/foo/bar foo.bar.example.com
example.net/foo/bar example.net
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment