views:

195

answers:

2

Given the pattern ^[a-zA-Z0-9 .\-_]+$ and the string te\\st, why is the match positive? I'm using this to validate usernames and I don't want people to put slashes in their usernames, it messes with URLs.

I'm calling ereg($pattern, $username), running PHP version 5.2.8.

+7  A: 

ereg is crazy. I recommend avoiding it. You should try using preg_match for this:

$count = preg_match('/^[a-zA-Z0-9 .\-_]+$/', 'te/\st', $matches);
print_r($matches); // empty array (no matches)
print $count; // 0 (no matches)
Paolo Bergantino
Thanks, that worked :)
Aistina
+3  A: 

^[a-zA-Z0-9 ._-]+$

Will work as well. To match a literal - in a character class it is usually safest to place it right before the ending ], or right after the opening [ when using ereg (POSIX). You should be able to escape out the - but for some reason when escaping it directly after the . seems to fail. Anyway there is a solution if you must use ereg. Really good question as to why that fails, the . should just be a normal character within the character class. Ereg is buggy.

Further reference.

And if you have the choice use preg (PCRE)...

Gnatz