PHP function to get the subdomain of a URL

Here’s a one line solution:

array_shift((explode('.', $_SERVER['HTTP_HOST'])));

Or using your example:

array_shift((explode('.', 'en.example.com')));

EDIT: Fixed “only variables should be passed by reference” by adding double parenthesis.

EDIT 2: Starting from PHP 5.4 you can simply do:

explode('.', 'en.example.com')[0];

Leave a Comment