When using user_save to create new user, you want to have username unique, if you are importing data or just want to be safe that someone hasn't have chosen username you already have in DB (and not to get nasty error PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry...). Here is some nice code to run on that username variable before saving an object.
function _prepare_unique_user_name($orig_name) {
$name = '';
if ($orig_name) {
/* filter characters (look at user_validate_name) */
preg_match_all("/[\x{80}-\x{F7} a-z0-9@_.'-]/i", $orig_name, $f_result);
if (isset($f_result[0]) && count($f_result[0])) {
$name = implode('', $f_result[0]);
/* remove multiple spaces and trim the name */
$name = trim($name);
$name = preg_replace('/[ ]+/', ' ', $name);
if ($name) {
/* check length (reserve 3 characters for number in next step) */
$name = substr($name, 0, USERNAME_MAX_LENGTH - 3);
/* check if the name is unique */
$i = 0;
do {
$query = db_select('users', 'u');
$query->addExpression('count(*)', 'matches');
$query->condition('u.name', (++$i) == 1 ? $name : $name.$i);
$matches = $query->execute()->fetchField();
} while ($matches);
if ($i > 1) {
$name.= $i;
}
}
}
}
return $name;
}