This is untested code, but it should be about right in principle. Put this into the index.php file right at the top. You may want to consider whether www variants of this URL need to be redirected, so you might want to consider writing a bit more code to normalize the HTTP_HOST variable.

It might or might not work, but as written it would fail with a parse error. Nobody who understood PHP and client/server protocols would write anything like that. Trying to make the code simpler will probably make it wrong, resulting in intermittent failures.

I have not tried it. The only issue I had was that I want www at all times. At no time should the domain be naked. I'm actually going to update the .htaccess file to make that so, but Imnot sure how your piece above will affect that? Im referrig to this:

// REMOVE www. IF IT IS THERE
$host = preg_replace($rgx, NULL, $_SERVER['HTTP_HOST']);

Do you know why you want www at all times? It is a subdomain, and it may or may not matter depending on your application and your server settings.

The process we are trying here is called "normalization." So we can remove the "www" if it is there, then we have a "naked" domain. With that we can add the "www" back and thereby avoid www.www.domain, etc.