-3

I want to take in any URL as input, and output just the domain name, so no trailing slash after the .com or .co.uk etc) and also remove the www. and whatever comes before it (noting that there may not be a www.).

Examples:

http://google.com/dir1/dir2/index.php -> google.com https://www.wonderfulworld.co.uk?a=1 -> wonderfulworld.co.uk

I will be using the preg_replace method in PHP.

Keir Simmons
  • 1,634
  • 7
  • 21
  • 37
  • post all the possible examples. – Avinash Raj Jul 24 '14 at 15:37
  • 1
    *"I will be using the `preg_replace` method in PHP."* - oh? – Funk Forty Niner Jul 24 '14 at 15:39
  • @AvinashRaj The URLs will be taken in as user input, so it could be anything that is a legal URL. – Keir Simmons Jul 24 '14 at 15:44
  • @Fred-ii- not sure how that's at all helpful? – Keir Simmons Jul 24 '14 at 15:44
  • What Regex have you tried? If you're unsure how to write a regex in the first place maybe read up on them and use a site like http://rubular.com to test them. – Travis Pessetto Jul 24 '14 at 15:46
  • Why are you saying "I" will be using... then? Show us what you've tried and where you think it's failing. As it stands, this is asking for code; *do* correct me if I'm wrong. – Funk Forty Niner Jul 24 '14 at 15:47
  • I should be fine with the start of the URL (http:// and www) but am unsure how to match the domain's suffix (.com or .co.uk). I do not know what the different variations are and what I should watch out for, for example not just matching . followed by 3 characters or . followed by 2 followed by . followed by 2 again etc. – Keir Simmons Jul 24 '14 at 15:49
  • 1
    possible duplicate of [Parsing Domain From URL In PHP](http://stackoverflow.com/questions/276516/parsing-domain-from-url-in-php) – MH2K9 Jul 24 '14 at 15:52

1 Answers1

4

Instead of preg_replace you can use parse_url

$url = 'http://google.com/dir1/dir2/index.php';
$parse = parse_url($url);
print $parse['host'];

Output:

google.com

MH2K9
  • 11,951
  • 7
  • 32
  • 49
  • Thank you, I wasn't aware of that method. I'll need to tweak it slightly to remove www and www3 etc but apart from that it's perfect! – Keir Simmons Jul 24 '14 at 15:53