Skip to content
Advertisement

Generate random username based on full name php

I want to grab the first name in lowercase then concatenate the first two characters after the space and finally concatenate that with a random number from 0 to 100. So if my name is "Mike Test" I want the output to be: mikete3

function random_username($string) {
    $pattern = " ";
    $firstPart = strstr(strtolower($string), $pattern, true);
    $secondPart = substr(strstr(strtolower($string), $pattern, false), 0, 3);
    $nrRand = rand(0, 100);

    $username = $firstPart.$secondPart.$nrRand;
    return $username;
}

echo random_username("Mike Test");

My function outputs “mike te84” and I don’t know how to remove that space.

Advertisement

Answer

Try this, always use trim to remove extra space.

function random_username($string) {
$pattern = " ";
$firstPart = strstr(strtolower($string), $pattern, true);
$secondPart = substr(strstr(strtolower($string), $pattern, false), 0,3);
$nrRand = rand(0, 100);

$username = trim($firstPart).trim($secondPart).trim($nrRand);
return $username;
}

echo random_username("Mike Test");
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement