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 :)

3
  • [As a quick note] I'll be using a string/variable that will store the domain ($var = "domain.com/";). Commented Jan 21, 2011 at 19:43
  • Just out of curiosity, why are You trying do that? Commented Jan 21, 2011 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. Commented Jan 21, 2011 at 19:48

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

I want to go about stripping the "http://" and any domain extension such as ".com" or ".net". Thanks :)
1

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

1 Comment

Gumbo explains it better above, go with that.
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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.