Possible Duplicate:
Php function to determine if a string consist of only alphanumerical characters?
I need to validate the string using PHP and regexpresisons
string can be min. 4 chars, up to 64 and needs to be only aplphanumeric
all I got so far:
/^[A-Za-z0-9]{4,64}$/
Your regex is correct (assuming you only want to match ASCII alphanumerics), so you're probably using it incorrectly. To check whether a string $subject
matches this regex, use
if (preg_match('/^[A-Z0-9]{4,64}$/i', $subject)) {
# Successful match
} else {
# Match attempt failed
}
Note the /i
option to make the regex case-insensitive. If you also want to match other letters/digits, use /^[\p{L}\p{N}]{4,64}$/
as your regex.
if (preg_match('/^[a-z0-9]{4,64}$/i', $subject)) {
# Successful match
} else {
# Match attempt failed
}
That's about as minimal as you can make it, though it does incur the regex overhad. Anything would would be more complicated, e.g:
$str = '....';
if (strlen($str) >= 4) && (strlen($str) <= 64) {
if (function_to_detect_non_alphanum_chars($str)) {
... bad string ...
}
}