auto generate username from name and last name


/ Published in: PHP
Save to your folder(s)

In my app, we have to auto-generate usernames for our users, here is the code I did.


Copy this code and paste it in your HTML
  1. <?php
  2. function generarUsername($nombre, apellido_paterno, $apellido_materno, $max_size = 8)
  3. {
  4. $tentativo = false;
  5. $i = 0;
  6. $n = substr($nombre, 0, 1);
  7. while($tentativo == false && $n != $nombre && $i<15)
  8. {
  9. $a = $apellido_paterno.substr($apellido_materno, 0, $i);
  10. $n = substr($nombre, 0, (strlen($a) + strlen($n) > $max_size)?(strlen($n) + 1):1);
  11. $tentativo = substr($n.$a, 0, $max_size);
  12.  
  13. if(self::getByUsername($tentativo)){
  14. //This function check if the tentative username is available
  15. $tentativo = false;
  16. }
  17. $i++;
  18. }
  19. return $tentativo;
  20. }
  21. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.