简体   繁体   中英

Regular Expressions and preg_match()

I am insanely green with regular expressions. Here is what I am trying to accomplish: I want to require an 8 character password that allows upper and lowercase letters, numbers and !@#$%^&*-_ characters. Here is what I have that doesn't appear to be working:

preg_match('([A-za-z0-9-_!@#$%^&*]{8,})', $password)

Am I missing something really obvious?

Update: Yes, I was missing something really obvious - the open bracket [. However it still returns true when I use characters like a single quote or bracket. (Which are what I am trying to avoid.)

Basically you miss an opening [ character group bracket here:

              ↓
 preg_match('([A-za-z0-9-_!@#$%^&*()]{8,})', $password)

And you should also use delimiters . The parens will behave as such, but it's better to use a different pair to avoid ambiguity with a capture group:

 preg_match('/^([A-za-z0-9-_!@#$%^&*()]{8,})$/', $password)

This also adds start ^ and end $ assertions to match the whole string.

This may be easier to break into individual rules. Ie a rule to check if the password is at least 8 characters long, another to check for an uppercase, another for lowercase, etc.

Also, it looks like you have some special characters in terms of regular expressions without any escaping. For example, the * character has special meaning in regular expressions other than some special cases. It either needs to be escaped \\* or in brackets [*]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM