Running parse_url () on a line that cannot contain a protocol

I am trying to get a domain name and TLD (without a subdomain) from a string of a user's URL, which may or may not have a protocol, directories, subdomains, file names, etc.

In other words, given any of the following:

example.com www.example.com sub.example.com example.com/whatever/hey.html http://example.com https://subdomain.example.com ftp://example.com/whatever/hey.html 

I always need: example.com .

Now this is what I am doing:

 $hostParts = explode('.', parse_url($URL, PHP_URL_HOST)); $tld = array_pop($hostParts); $domain = array_pop($hostParts); $domain = $domain . "." . $tld; 

However, if the URL is provided without a protocol, it is interrupted. Why parse_url cannot get the host in this situation?

+2
source share
1 answer

By definition, a URL contains a protocol or scheme. Check that // and if not, add // to the line. This may be different in PHP <5.4.7, so maybe add http: // if there is no protocol.

+2
source

Source: https://habr.com/ru/post/1013484/


All Articles