PHP: Simple username generator
Posted on April 25th, 2008 in PHP
Here is a simple function I wrote to generate a username based on user’s first and last name. This function will concatenate the first 5 characters of the first name to the first character of the last name. I used the explode function to split names with more than one word, and ran loops to concatenate them back to trim spaces.
function generate_username($first_name = '', $last_name = ''){
$f_array = explode(' ', $first_name);
$l_array = explode(' ', $last_name);
foreach($f_array as $f_bit) $fname .= $f_bit;
foreach($l_array as $l_bit) $lname .= $l_bit;
return strtolower(substr($fname, 0, 5) . substr($lname, 0, 1));
}
Usage:
$username = generate_username('Juan Miguel', 'De Vega');
returns: “juanmd”
Click here to see it in action.
Download the full source code.
This post has 3 comments
May 1st, 2008
Very useful function. I am using it to generate usernames in my web app. Keep up!
May 22nd, 2008
you forgot to put brackets on your loops
May 23rd, 2008
you can actually drop the bracket when performing loops same with if statements, but I don’t recommend dropping it when coding large applications. Brackets make code easier to read and make debugging a lot easier.