fr3d fr3d - 2 months ago 12
PHP Question

Get .tld from URL via PHP

I need a short way to get the .tld from an URL via PHP.
E.g. www.domain.com/site, the PHP should post: tld is: .com.
I hope you guys can help me.

Thanks

Answer

Use parse_url() function to get host part of the url then explode by . and get last element of an array

Example below:

$url = 'http://www.domain.com/site';
echo end(explode(".", parse_url($url, PHP_URL_HOST))); // echos "com"

Before that it would be nice to check if $url is actual URL with filter_var for example

Comments