使用PHP函数创建没有空格的用户名..但不知何故空间正在添加?

I have a PHP script that generates a username based on when someone logs in via Facebook.

I am calling it like this:

$username = create_username($facebook_data['name']);

And the function is:

function create_username($username)
{
global $db;

$valid = false;
$counter = 0;
$new_username = str_replace(' ', '', $username);

while (!$valid) 
{
    $counter++;
    $is_username = $db->count_rows('users', "WHERE username='" . $new_username . "'");

    if ($is_username)
    {
        $new_username = $username . $counter;
    }
    else 
    {
        $valid = true;
    }
}

$new_username = strtolower($new_username);
return $new_username;

}

The problem is, if I have a user that is called "johnsmith" and someone with the name of "john smith" registers, it generates a username that is "john smith1" instead of "johnsmith1". What am I doing wrong?

I even did a

var_dump($facebook_data['name']) 

and it is returned as "John Smith", with no extra spaces or anything.

Your are using the $username variable in your loop so you will get a username with spaces if the original username already exists.

Below I've created a $clean_username variable that can be appended to so you get username6 instead of username123456 for example:

function create_username($username)
{
   global $db;

   $valid = false;
   $counter = 0;
   $clean_username = $new_username = str_replace(' ', '', $username);

   while (!$valid) 
   {
       $counter++;
       $is_username = $db->count_rows('users', "WHERE username='" . $new_username . "'");

       if ($is_username)
       {
           $new_username = $clean_username . $counter;
       }  
       else 
       {
           $valid = true;
       }
   }

   $new_username = strtolower($new_username);
   return $new_username;
}
if ($is_username)
{
    $new_username = $username . $counter;
}

correct is

if ($is_username)
{
    $new_username = $new_username . $counter;
}