rainjam Posted August 9, 2012 Share Posted August 9, 2012 I'm trying to write a password generator which allows you to force numbers to appear in the password. It currently generates 20 or so at a time and then you can pick one. So after each iteration I need to examine the password that's been generated: if the "force numbers" option is ticked, and there aren't numbers in this password, it will swap a few characters at random for digits. To test for whether a password string has ended up with numbers in it, I thought regex would work best, but I've never used them before... after a bit of digging around, I found "/^[0-9]+$/" to match digits within a string. Which seems like it should work, but doesn't: $test_thing = "hadsdjkl"; $test_thing2 = "hs4ifhkb7ahnj4ks"; $preg_str = "/^[0-9]+$/"; echo $test_thing . " tests " . preg_match($preg_str, $test_thing) . " for numbers<br />"; echo $test_thing2 . " tests " . preg_match($preg_str, $test_thing2) . " for numbers<br />"; Output: hadsdjkl tests 0 for numbers hs4ifhkb7ahnj4ks tests 0 for numbers I'm probably being stupid, but shouldn't $test_thing2 return a positive match? Quote Link to comment Share on other sites More sharing options...
DavidAM Posted August 9, 2012 Share Posted August 9, 2012 "/^[0-9]+$/" The caret ("^") at the beginning of the RegExp, anchors it the the start of the string. The dollar-sign ("$") at the end of the RegExp, anchors it to the end of the string. So that expression will only match a string that is composed entirely of digits (one or more). If you take the caret and dollar-sign out, it will match one or more digits anywhere in the string. You will not get any indication of how many total digits are in the string, so it will not work if the requirement is "2 or more digits"; and it will not indicate if all of the found digits are consecutive: i.e. it will match "a1b" and "a11b" and "a1b2". Note that preg_match returns the number of full pattern matches found. But, it will always stop as soon as it finds a match, so the return value will never be greater than one. preg_match_all will find all pattern matches and return the number found. But again, it is the count of the number pattern matches (one or more consecutive digits) and not the count of the total number of digits in the string. i.e. in the examples I gave above, the return values would be: 1, 1, and 2. Quote Link to comment Share on other sites More sharing options...
rainjam Posted August 10, 2012 Author Share Posted August 10, 2012 Ah, that makes perfect sense - thank you! In this example I'm only concerned that there's at least one number, so preg_match() will work fine for this. Cheers for the help Nick Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.