Is it possible to dynamically redirect URL using htaccess?

StackOverflow has already an answer for your question: https://stackoverflow.com/questions/2551553/htaccess-redirecting-dynamic-url

I guess that this should do the trick:

RewriteRule ^(\d+)$ /?p=$1 [R=302,L]