1

If I have a variable that contains a URL, then how can I get the base URL? That is,

$url = 'http://www.domain.com/some/stuff/that/I/do/not/want/';
$base_url = some_clever_function($url);
// $base_url is now set equal to 'domain.com'

How can I do this?

nickb
  • 59,313
  • 13
  • 108
  • 143
Ajay Mohite
  • 119
  • 3
  • 13

2 Answers2

12

parse_url will be able to extract the host for you.

It has the second argument with the help of which you can extract different parts of URL. To extract host, use parse_url the following way:

$host = parse_url($url, PHP_URL_HOST);
madfriend
  • 2,400
  • 1
  • 20
  • 26
Sebastian Paaske Tørholm
  • 49,493
  • 11
  • 100
  • 118
-3
$url = 'http://google.com/dhasjkdas/sadsdds/sdda/sdads.html';
$parse = parse_url($url);
print $parse['host']; // prints 'google.com'

Second method

<?php
// get host name from URL
preg_match("/^(http:\/\/)?([^\/]+)/i",
    "http://www.php.net/index.html", $matches);
$host = $matches[2];

// get last two segments of host name
preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches);
echo "domain name is: {$matches[0]}\n";

/* Output is php.net */


?>  
Ruzbeh Irani
  • 2,318
  • 18
  • 10
  • 1
    If you're going to blatantly copy code, you should at least give credit to [the original authors (Ex. #3)](http://php.net/preg_match). – nickb Aug 06 '12 at 19:13
  • https? and second example again is missing optional protocol – madfriend Aug 06 '12 at 19:14