2

I was wondering of the best way of removing certain things from a domain using PHP.

For example:

"http://mydomain.com/" into "mydomain"

or

"http://mydomain.co.uk/" into "mydomain"

I'm looking for a quick function that will allow me to remove such things as:

"http://", "www.", ".com", ".co.uk", ".net", ".org", "/" etc

Thanks in advance :)

  • [As a quick note] I'll be using a string/variable that will store the domain ($var = "http://domain.com/";). –  Jan 21 '11 at 19:43
  • Just out of curiosity, why are You trying do that? – Mikk Jan 21 '11 at 19:46
  • It's just for adding info to a database on a new project I'm working on. When I print the data in profile pages etc I don't want to have incorrect domain extensions, So I want to phrase them myself. –  Jan 21 '11 at 19:48

4 Answers4

7

To get the host part of a URL use parse_url:

$host = parse_url($url, PHP_URL_HOST);

And for the rest see my answer to Remove domain extension.

Community
  • 1
  • 1
Gumbo
  • 643,351
  • 109
  • 780
  • 844
1

Could you use string replace?

str_replace('http://', '');

This would strip out 'http://' from a string. All you would have to do first is get the current url of the page and pass it through any string replace you wanted to..

iamjonesy
  • 24,732
  • 40
  • 139
  • 206
  • I want to go about stripping the "http://" and any domain extension such as ".com" or ".net". Thanks :) –  Jan 21 '11 at 19:50
1

I would str_replace out the 'http://' and then explode the periods in the full domain name.

Hoatzin
  • 1,466
  • 13
  • 14
0

You can combine parse_url() and str_* functions, but you'll never have correct result if you need cut domain zone (.com, .net, etc.) from your result.

For example:

parse_url('http://mydomain.co.uk/', PHP_URL_HOST); // will return 'mydomain.co.uk'

You need use library that uses Public Suffix List for handle such situations. I recomend TLDExtract.

Here is a sample code:

$extract = new LayerShifter\TLDExtract\Extract();

$result = $extract->parse('mydomain.co.uk');
$result->getHostname(); // will return 'mydomain'
$result->getSuffix(); // will return 'co.uk'
$result->getFullHost(); // will return 'mydomain.co.uk'
$result->getRegistrableDomain(); // will return 'mydomain.co.uk'
Oleksandr Fediashov
  • 4,315
  • 1
  • 24
  • 42