0

I'm a complete novice when it comes to regex. Could someone help me convert the following expression to preg?

ereg('[a-zA-Z0-9]+[[:punct:]]+', $password)

An explanation to accompany any solution would be especially useful!!!!

Gumbo
  • 643,351
  • 109
  • 780
  • 844
musoNic80
  • 3,678
  • 9
  • 40
  • 48
  • Just out of curiosity, what is your intent for this regular expression? It looks like what it will match is 1 or more letters or numbers, followed by one or more punctuation marks. Is that what you want for a password? – Craig Trader Jun 18 '10 at 13:27
  • I wanted it to force the user to use upper and lowercase letters, at least one number and at least one punctuation mark. Is what I've got incorrect? – musoNic80 Jun 18 '10 at 13:34
  • You can't do what you want with a regular expression. You'll need to actually check for the presence of each character class (upper, lower, digit, punctuation), and fail if one is missing. – Craig Trader Jun 18 '10 at 14:25
  • Could you explain to me in more detail? Should I therefore run the password through 4 separate regex? – musoNic80 Jun 18 '10 at 15:02

2 Answers2

1
preg_match('/[a-zA-Z0-9]+[[:punct:]]+/', $password)

You simply put a / at the beginning and a / at the end. Following the / at the end you can put some different options:

i - case insensitive

g - do a gloabl search

For more information in the beautiful world of regex in PHP, check out this:

http://www.regular-expressions.info/php.html

Bob Fincheimer
  • 17,978
  • 1
  • 29
  • 54
1

To answer your real question, you'd need to structure your code like:

if ( preg_match( '/[a-z]+/', $password ) && 
  preg_match( '/[A-Z]+/', $password ) && 
  preg_match( '/[0-9]+/', $password ) && 
  preg_match( '/[[:punct:]]+/', $password ) ) ...

If you wanted to ensure the presence of at least one lowercase letter, at least one uppercase letter, at least one digit, and at least one punctuation character in your password.

Other questions you should read:

Community
  • 1
  • 1
Craig Trader
  • 15,507
  • 6
  • 37
  • 55