Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

url

php

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.

like image 680
JohnUS Avatar asked Feb 20 '12 16:02

JohnUS


People also ask

How do I remove http and www from url?

To remove http:// or https:// from a url, call the replace() method with the following regular expression - /^https?:\/\// and an empty string as parameters. The replace method will return a new string, where the http:// part is removed. Copied!

How do I remove the last slash from a url?

Then preg_replace('{/$}', '', $_SERVER['REQUEST_URI']) will remove the slash and hand over to header() to redirect. The exit() function is important to stop any further code execution.


2 Answers

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

like image 150
webbiedave Avatar answered Sep 22 '22 09:09

webbiedave


$str = 'http://www.google.com/'; $str = preg_replace('#^https?://#', '', rtrim($str,'/')); echo $str; // www.google.com 
like image 44
Mahdi Avatar answered Sep 19 '22 09:09

Mahdi