Search code examples
phpsubmission

Regular Expression does not check against passwords well


I need to check if the passwords ONLY contain ENGLISH numbers and letters. I use the following regular expression:

if (!preg_match("^[A-Za-z0-9 _]*$^", $_POST['password']))
{
// show error
}
{

but this does not work and allows other languages characters without stopping the submission. what is the problem?


Solution

  • Remove the ^ at the end of the preg_match. ^ means (if found as the first character) beginning, if it is a the end, it has the meaning that the character ^ should be present but because $ appears before it, its meaning is confusing and could mean several thing, the most "possible" one is after the end the character ^.

    Use regexpal.com to test your regular expression.

    Actually I would change it to this:

    if (preg_match("[^A-Za-z0-9 _]", $_POST['password']))
    {
      // invalid character
    }