2

I would like to get the host name of any url for example if i've the following url

$url = "http://www.google.com";

then i want to get only google what is after dot . and before extension dot . so that it can be applied for all types of urls.

so the results should be google ! i think this might needs regex or somehow any idea how to do it , Thanks.

2
  • 2
    What if the URI has (sub)domains prefixed? i,e http://office1.dept1.google.com Commented Oct 2, 2012 at 11:12
  • Oops ! you are right that would fail on sub domains ! Commented Oct 2, 2012 at 11:14

2 Answers 2

8

You can try

echo __extractName("http://google.com"); 
echo __extractName("http://office1.dept1.google.com");
echo __extractName("http://google.co.uk");


function __extractName($url)
{
  $domain = parse_url($url , PHP_URL_HOST);
  if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $list)) {
    return substr($list['domain'], 0,strpos($list['domain'], "."));
  }
  return false;
}

Output

google
google 
google 
Sign up to request clarification or add additional context in comments.

1 Comment

+ 1, What about localhost without any domain alias?
2

You should have a look at PHP's parse_url() function which returns an associative array of the various components that constitute a URL.

$url = "http://www.google.com";
print_r(parse_url($url)); 

Will echo the following array.

Array ( [scheme] => http [host] => www.google.com ) 

The above function will just give you a start. Check into the following Stackoverflow archives on how to take it up from here.

PHP Getting Domain Name From Subdomain

Get domain name (not subdomain) in php

PHP function to get the subdomain of a URL

EDIT (few more archives - I'm not sure what you googled/tried)

how to get domain name from URL

Extract Scheme and Host from HTTP_REFERER

3 Comments

Note that you can also pass PHP_URL_HOST as the second parameter, and it will just return the hostname instead of an array.
well based on your idea and very amazing archives, i will use 'explode' and then will results an array where i can print only the exact part of url i want. ~ thanks
for sure. Next time around, ensure that you "google" :) Lest you'll either be downvoted or your question will be closed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.