Reputation: 6501
Im using a regex on PHP to convert an url to a domain like below
function getDomainFromUrl($url) {
$pieces = parse_url($url);
$domain = isset($pieces['host']) ? $pieces['host'] : '';
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;
}
Now I want to get domain with its subdomain. What should I do on my regex?
Now:
http://subdomain.example.com -> returns to example.com
Expected:
subomain.example.com
Last but most important part for me:
if url has www.
subdomain should be removed. I don't want to get www.
Upvotes: 1
Views: 223
Reputation: 672
How about this?
function getDomainFromUrl($url) {
if (!filter_var($url, FILTER_VALIDATE_URL)) {
$url = 'http://' . $url;
}
$host = parse_url($url, PHP_URL_HOST);
return preg_replace('/^www\./', '', $host);
}
Upvotes: 1
Reputation: 350
print get_domain("http://subomain.example.com"); // outputs 'example.com'
function get_domain($url)
{
$pieces = parse_url($url);
$domain = isset($pieces['host']) ? $pieces['host'] : '';
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;
}
Upvotes: 1