On my registration page I need to validate the usernames as alphanumeric only, but also with optional underscores. I\'ve come up with this:
function validate
Your own solution is perfectly fine.
preg_match uses Perl-like regular expressions, in which the character class \w defined to match exactly what you need:
preg_match
\w
\w - Match a "word" character (alphanumeric plus "_")
(source)