@OctoberWindNov 15.2012 — #Those checks are all well and good, if all you want to know if is the string contains "a letter" , "a number" or "a letter, number, hyphen, period, or underscore".
I'm going to assume this is for validating some type of login or password?
If that's the case, you probably want to check for things OTHER than what you want.
Take a look at these examples:
[code=php] $test_string = "Str1ng-t0_ch3ck."; $test_string_words = "Stringtocheck"; $test_string_numbers = "12345"; $test_string_mixed = "Str1ng t0 ch3ck."; // note the added spaces; need to add s to the regex patterns to match this
$reg1 = preg_match("/[^0-9]/", $test_string); // Only numbers $reg1a = preg_match("/[^0-9]/", $test_string_numbers); // Only numbers
$reg2 = preg_match("/[^a-z]/i", $test_string); // Only letters $reg2a = preg_match("/[^a-z]/i", $test_string_words); // Only letters
$reg3 = preg_match("/[^a-z0-9-._]/i", $test_string); // numbers, letters and -._
$reg4 = preg_match("/[^w-._]/i", $test_string_mixed); // numbers, letters and -._
/* preg_match returns int(1) if it finds a match to the pattern or int(0) if it does not find a match. since these checks are checking for NOT IN THE PATTERN, then (if $var === 0) "passes" the regex and (if $var === 1) "fails" {three "equal signs" matches exactly the type int()} ------------ reg1 (it found something other than just numbers) 1 ------------ ------------ reg1a (it found only numbers)
------------ ------------ reg2 (it found something other than just letters) 1 ------------ ------------ reg2a (it found only letters)
------------ ------------ reg3 (it found only the acceptable characters)
------------ ------------ reg4 (condensed "word boundries (letter and numbers) plus the extra characters") 1 ------------