How to remove http://, www and slash from URL in PHP?

Try this, it will remove what you wanted (http:://, www and trailing slash) but will retain other subdomains such as example.google.com

$host = parse_url('http://www.google.com', PHP_URL_HOST);
$host = preg_replace('/^(www\.)/i', '', $host);

Or as a one-liner:

$host = preg_replace('/^(www\.)/i', '', parse_url('http://www.google.com', PHP_URL_HOST));

$str = 'http://www.google.com/';
$str = preg_replace('#^https?://#', '', rtrim($str,'/'));
echo $str; // www.google.com

$input = 'www.google.co.uk/';

// in case scheme relative URI is passed, e.g., //www.google.com/
$input = trim($input, '/');

// If scheme not included, prepend it
if (!preg_match('#^http(s)?://#', $input)) {
    $input = 'http://' . $input;
}

$urlParts = parse_url($input);

// remove www
$domain = preg_replace('/^www\./', '', $urlParts['host']);

echo $domain;

// output: google.co.uk

Works correctly with all your example inputs.


There are lots of ways grab the domain out of a url I've posted 4 ways below starting from the shortest to the longest.

#1

function urlToDomain($url) {
   return implode(array_slice(explode('/', preg_replace('/https?:\/\/(www\.)?/', '', $url)), 0, 1));
}
echo urlToDomain('http://www.example.com/directory/index.php?query=true');

#2

function urlToDomain($url) {
   $domain = explode('/', preg_replace('/https?:\/\/(www\.)?/', '', $url));
   return $domain['0'];
}
echo urlToDomain('http://www.example.com/directory/index.php?query=true');

#3

function urlToDomain($url) {
   $domain = preg_replace('/https?:\/\/(www\.)?/', '', $url);
   if ( strpos($domain, '/') !== false ) {
      $explode = explode('/', $domain);
      $domain  = $explode['0'];
   }
   return $domain;
}
echo urlToDomain('http://www.example.com/directory/index.php?query=true');

#4

function urlToDomain($url) {
   if ( substr($url, 0, 8) == 'https://' ) {
      $url = substr($url, 8);
   }
   if ( substr($url, 0, 7) == 'http://' ) {
      $url = substr($url, 7);
   }
   if ( substr($url, 0, 4) == 'www.' ) {
      $url = substr($url, 4);
   }
   if ( strpos($url, '/') !== false ) {
      $explode = explode('/', $url);
      $url     = $explode['0'];
   }
   return $url;
}
echo urlToDomain('http://www.example.com/directory/index.php?query=true');

All of the functions above return the same response: example.com

Tags:

Php

Url