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

Issue

I need a php function which produce a pure domain name from URL. So this function must be remove http://, www and /(slash) parts from URL if these parts exists. Here is example input and outputs:
Input – > http://www.google.com/ | Output -> google.com
Input – > http://google.com/ | Output -> google.com
Input – > www.google.com/ | Output -> google.com
Input – > google.com/ | Output -> google.com
Input – > google.com | Output -> google.com

I checked parse_url function, but doesn’t return what I need.
Since, I’m beginner in PHP, it was difficult for me. If you have any idea, please answer.
Thanx in advance.

Solution

$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.

Answered By – webbiedave

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published