Regex fail

I am having a strange problem where a tiny percentage of usernames are slipping through the regex validation somehow, by having spaces in their usernames.

My understanding is that this regex will be true for alphanumeric strings between 5 and 20 characters. In fact I can’t get it to slip up - so how does anyone else get past it?

function validUsername($user)
    return (preg_match('/^[a-zA-Z0-9]{5,20}$/', $user));

$tests = array('something', 'something else');

foreach ($tests as $v)
    echo $v . ' '; 
    echo (!validUsername($v)) ? 'reject' : 'approve';
    echo '<br />';

There is no way for anything with a space to get past that.


Even the demonstration code you posted works as expected. :slight_smile:

I know, its so weird that I get these sporadic occurrences, when I can’t get past the function myself.

I did obviously consider the possibility that the usernames are changing somewhere else in the application without the validation, but there simply is no other place that the username can be set, apart from on registration.

oh well - once in a blue moon I can live with, i’m sure one day i’ll have a ah-ha moment. Thanks for inputs.

Is the code called from an include file, and is that include call itself dependent upon an unforeseen condition elsewhere?

Or is it part of a class?

The validation is invoked within a class, but the way I extracted the example code above is effectively the exact same procedure as the class method.

How about giving us some of the usernames that manage to slip through the net?

and there is my ah-ha moment… All of the problematic usernames are older than I thought they were… I think the regex was updated 18 months or more ago none have come through since then.


btw-that regex does allow a trailing newline character. If that’s not desired, use the D flag.

var_dump(preg_match('/^[a-zA-Z0-9]{5,20}$/', "testing\
var_dump(preg_match('/^[a-zA-Z0-9]{5,20}$/D', "testing\