Well, to start with, you'll need to implement Wild Card DNS. Then you'd need to insure mod_rewrite is installed and working.
You also need to instruct Apache to treat *.domain.com as domain.com, typically in a <Virtualhost> container in an included file for httpd.conf, or in httpd.conf itself.
And THEN and only then can you worry about your rewrite rules ... which might look something like this:
<IfModule mod_rewrite.c>
Options +FollowSymLinks
Options +Indexes
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !www.domain.com$ [NC]
RewriteCond %{HTTP_HOST} ^(www.)?([a-z0-9-]+).domain.com [NC]
RewriteRule (.*) %2/$1 [L]
</IfModule>