I'm new here, having a little trouble with a basic regular expression. I'm pretty sure I am coding it right, but its not doing what I'm expecting.
I'm trying to write some code to check that the user names are only alphanumeric characters.
Here is the code:
$userNames = array("shouldwork","should not work","shouldwork2","badusername!");
foreach($userNames as $x => $strval)
{
$valid = ereg('[[:alnum:]]', $strval);
if(!$valid)
echo "Index: {$x} Value: {$strval} is an invalid username!<br/> \n";
else
{
echo "Index: {$x} Value: {$strval} is a valid username!<br/> \n";
}
}
Here is the output I am getting:
Index: 0 Value: shouldwork is a valid username!
Index: 1 Value: should not work is a valid username!
Index: 2 Value: shouldwork2 is a valid username!
Index: 3 Value: badusername! is a valid username!
So its telling me they are all valid. I was only expecting index 0 and 2 to work, since index 1 has spaces and index 3 has a '!'.
I am getting the reg exp I am using from a book. According to the book this is how you do it. But the more I think about it, maybe this reg exp is only looking to if there are any alphanumerics and not if they are all alphanumerics?? Maybe the book is wrong.