$re = '/^(?=.{1,39}$)^[a-zA-Z\d]+(?:-[a-zA-Z\d]+)*$/m';
$str = '-username
_username_
__us_ername
us_er
username-
1user--name
132uname-
-uname1234
-username-
user--name
av34axc-
1234567890A1234567890B1234567890C1234567890D
Username
a-a
aBc
BaC
1-1
1-2-3-4
q-1-2-3
q-q-q-q-q
username
123username123
username3123
1234
user-name
13-13
q1-q2-q3
a
A
1234567890A1234567890B1234567890C123456
1234567890A123456-7890B1234567890C12345';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
var_dump($matches);
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for PHP, please visit: http://php.net/manual/en/ref.pcre.php