检查字符串是否仅由字母数字字符组成的最佳方法是什么? [重复]
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}$/
可能重复: strong>
Php函数,用于确定字符串是否仅包含字母数字字符 ? p> blockquote>我需要使用PHP和regexpresisons验证字符串 p>
字符串可以是 分钟。 4个字符,最多64个,只需要只是aplphanumeric p>
我到目前为止所有这些: p>
/ ^ [A-Za z0-9] {4,64} $ / code> p> div>
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 ...
}
}