【发布时间】:2011-12-20 14:45:14
【问题描述】:
如何检测字符串中的非数字或非字母?
KY4R5EHCN5W476XXO5ER - 返回true
KY4R5EHCN5W472X**@**O5ER - 返回false
我知道答案是使用正则表达式,但我不知道该怎么做。我很讨厌正则表达式。任何帮助将不胜感激。
谢谢!
【问题讨论】:
标签: php regex string validation
如何检测字符串中的非数字或非字母?
KY4R5EHCN5W476XXO5ER - 返回true
KY4R5EHCN5W472X**@**O5ER - 返回false
我知道答案是使用正则表达式,但我不知道该怎么做。我很讨厌正则表达式。任何帮助将不胜感激。
谢谢!
【问题讨论】:
标签: php regex string validation
if (preg_match('/[^A-Z0-9]/', $string)) {
... some char other than A-Z, 0-9 detected
}
【讨论】:
i 在末尾,否则你不会得到小写字符。
detect a non number or non letter,尽管该示例只有大写字母。
if (preg_match('/[^a-z0-9]/i', $subject)) {
// Invalid characters
} else {
// Only letters and numbers
}
【讨论】:
^a-z0-9,因为您最后使用的是 i。
你可以用这个:
if (preg_match('/^([a-z0-9]+)$/iu', $string))
{
// all alpha and digits
}
else
{
// not all alpha and digits
}
【讨论】:
(preg_match('/^[A-Z0-9]+$/', $string) == 0)
如果要包含小写字符,请更改为 a-zA-Z0-9
如果字符串只包含 A-Z 和 0-9,这应该返回 true。
或
(preg_match('/[^A-Z0-9]/', $string) != 0)
应该做的差不多。
【讨论】:
ctype_alnum() 在检测字符串是否为纯字母数字(字母和数字)方面将比正则表达式快得多。
$str1 = 'KY4R5EHCN5W476XXO5ER';
$str2 = 'KY4R5EHCN5W472X*@*O5ER' ;
foreach (array($str1, $str2) as $str){
if (ctype_alnum($str)) {
echo "$str is alphanumeric\n" ;
}
else {
echo "$str is not just alphanumeric\n";
}
}
但是,请务必使用此处给出的正则表达式,因为这是一项有用的技能,尤其是当您后来决定还需要检查其他字符(如破折号)时。你会发现The Regex Coach 在试验它们时非常有用。
$str = 'KY4R5EHCN5W476XXO5ER' ;
$ut = microtime(true) ;
for ($i = 0 ; $i < 100000; $i++) {
$res = ctype_alnum($str) ;
}
$utCtype = microtime(true) ;
for ($i = 0 ; $i < 100000; $i++) {
$res = preg_match('/[a-z0-9]/i', $str) ;
}
$utEnd = microtime(true) ;
$utDiffCtype = $utCtype - $ut ;
$utDiffPreg = $utEnd - $utCtype;
echo "ctype: $utDiffCtype, preg: $utDiffPreg" ;
【讨论】:
使用这个正则表达式来兼容 unicode:
/^[\p{L}\p{N}]+$/u
【讨论】: