Search code examples
phpregexposix-ere

Why is this regular expression match positive?


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.


Solution

  • 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)