Hi everyone, I have a login form working great, until I found this strange error.
If a user enters the username as user name (with a space) the login script fails.
So I have tried using

$username = str_replace(' ', '', strtolower($username));

I thought the above would remove any spaces from the entered username and produce a single string.
It works when registering, but for some reason, it doesnt work on the login page.

Does anyone know why the above is not removing any spaces in the entered username.
Thanks
DM

Recommended Answers

All 4 Replies

try..

 $username = " this  is  user  name  ";
   $username = trim(str_replace(' ','',$username));
   echo $username;

for registration, try

  $username = preg_replace('/\s\s+/', '', $username);

Hi, this worked a treat :) thanks,
Can I ask one more question about only allowing alphnumeric values.
I would like to restrict the usernames to only allow alphanumeric data, letters and numbers.

I have a number of lines of code like below

$sname = str_replace("'", '', strtolower($sname));
$sname = str_replace('-', '', strtolower($sname));  

But there are many more characters I would like to dismiss from the users username.
How is this possible without having to create a seperate str_replace for each charachters

try,

$user2 = " this / ?  is ~~ + | $ ##  * 7 ) user  name  <br/>";

    $user2 = preg_replace('/[^a-zA-Z0-9 ]/s', '', $user2);
    $user2 = trim(str_replace(' ','',$user2));

    echo "<br/>".$user2."<br/>";

Let the preg_replace to get process first, and then the trim string replace. They cannot be condensed I think.. I don't have the chance to test it.. Please let me know if the codes above worked..

PHP is having good function ctype_alnum, which will do all stuff for you in one line.

<?php
$username = 'testing123';
if(ctype_alnum($username))
{
    echo 'Username is valid';
}
else
{
    echo 'Username is not valid';
}
?>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.