function to return unique username

Public

this function can be used to get unique user name for a drupal user
it takes name as argument
then it checks if username exists already in database
if yes, then it returns changes given name to make it unique
it can be used to user programmatically.

</> CopyGet raw version
php
  1. function _mymodule_unique_username($name, $uid = 0) {
  2. // Strip illegal characters.
  3. $name = preg_replace('/[^\x{80}-\x{F7} a-zA-Z0-9@_.\'-]/', '', $name);
  4.  
  5. // Strip leading and trailing spaces.
  6. $name = trim($name);
  7.  
  8. // Convert any other series of spaces to a single underscore.
  9. $name = preg_replace('/ +/', '_', $name);
  10.  
  11. // If there's nothing left use a default.
  12. $name = ('' === $name) ? t('user') : $name;
  13.  
  14. // Truncate to reasonable size.
  15. $name = (drupal_strlen($name) > (USERNAME_MAX_LENGTH - 10)) ? drupal_substr($name, 0, USERNAME_MAX_LENGTH - 11) : $name;
  16.  
  17. // Iterate until we find a unique name.
  18. $i = 0;
  19.  
  20. do {
  21. $new_name = empty($i) ? $name : $name . '_' . $i;
  22. $found = db_query_range("SELECT uid from {users} WHERE uid <> :uid AND name = :name", 0, 1, array(':uid' => $uid, ':name' => $new_name))->fetchAssoc();
  23. $i++;
  24. } while (!empty($found));
  25.  
  26. return $new_name;
  27. }

Comments

Rys Max's picture

  1. function gplus_sync_prepare_user_name($orig_name) {
  2. $name = '';
  3. if ($orig_name) {
  4. /* filter characters (look at user_validate_name) */
  5. preg_match_all("/[\x{80}-\x{F7} a-z0-9@_.'-]/i", $orig_name, $f_result);
  6. if (isset($f_result[0]) && count($f_result[0])) {
  7. $name = implode('', $f_result[0]);
  8. /* remove multiple spaces and trim the name */
  9. $name = trim($name);
  10. $name = preg_replace('/[ ]+/', ' ', $name);
  11. if ($name) {
  12. /* check length (reserve 3 characters for number in next step) */
  13. $name = substr($name, 0, USERNAME_MAX_LENGTH - 3);
  14. /* check if the name is unique */
  15. $i = 0;
  16. do {
  17. $query = db_select('users', 'u');
  18. $query->addExpression('count(*)', 'matches');
  19. $query->condition('u.name', (++$i) == 1 ? $name : $name.$i);
  20. $matches = $query->execute()->fetchField();
  21. } while ($matches);
  22. if ($i > 1) {
  23. $name.= $i;
  24. }
  25. }
  26. }
  27. }
  28. return $name;
  29. }