by Michael Hughes.
Is this via self-registration that the user is created? As I'm not sure how you're getting the 2 lastnames (Moodle only has 1 out of the box).
However the username field on the user object is "cleaned" inline with the defined requirements in lib/classes/user.php fill_properties_cache():
$fields['username'] = array('type' => PARAM_USERNAME, 'null' => NULL_NOT_ALLOWED);
The username is then passed through clean_param with this clean type, which will do a number of "fixes" (fix UTF-8 issues, trim whitespace, convert to lowercase) and then removes various other characters (see moodelib.php clean_param() ):
// Regular expression, eliminate all chars EXCEPT:Now you can set $CFG->extendedusernamechars (but read the config-dist.php)
// alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.