It all has to do with wilcards. You can add an A record for * that points to an address.
ex.
Make sure this is THE VERY LAST A record, otherwise you might break resolution for some records. This wildcard will match any third level domain that is not found previously in the zone.
Then server side, within you conf, add a server alias of
.2ndleveldomain.
This way apache matches all host header names.
You can then call a routine that does whatever dependent on the value of $HTTP_HOST.
If you have a host who will not add wildcards to you DNS records or to you virtualhost tags then I suggest you find a new host.