Jump to content

getting the domain of a url by parse_url


etrader

Recommended Posts

I have two questions:

 

1. Is it the best way to get the domain of a url by parse_url? or preg_match or str_replace can be better alternatives?

 

2. What is the best way to remove www from the domains? Note that the domain name itself may contain www too (like www.1www.com)

 

Thank for your attention  :shy:

1. parse_url is by far the best solution. Avoid preg_match whenever you can.

2.

$domain = ltrim(parse_url($url, PHP_URL_HOST), 'w.'); /*magic*/

 

This can become an issue if your domain is http://www.com (valid host name) but you can solve that like this:

 

$domain = 'www.' . ltrim(parse_url($url, PHP_URL_HOST), 'w.'); /*magic*/

 

This will do the following:

 

www.com =ltrim=> com => www.com
domain.top =ltrim=> domain.top => www.domain.top
www.domain.top =ltrim=> domain.top => www.domain.top

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.