[英]differentiate alphanumeric and alphabetic in php
i have two strings in a php i want to make following checks in that 我在PHP中有两个字符串,我想在其中进行以下检查
1) 4f74adce2a4d2 - contains ***alphanumerics***
2) getAllInfo - contains ***only alphabetic***
to check this i wrote a function but whatever value $pk contains among above , results into true only , but i want to differentiate between alphanumeric and alphabetic only
为了检查这一点,我写了一个函数,但是上面的任何值$ pk都包含在内,结果仅是true,但是i want to differentiate between alphanumeric and alphabetic only
<?php
if (ereg('[A-Za-z^0-9]', $pk)) {
return true;
} else if (ereg('[A-Za-z0-9]', $pk)) {
return false;
}
?>
Use the following two functions to detect whether a variable is alhpanumeric or alphabetic: 使用以下两个函数来检测变量是字母数字还是字母数字:
// Alphabetic
if(ctype_alpha($string)){
// This is Alphabetic
}
// Alphanumeric
if(ctype_alnum($string)){
// This is Alphanumeric
}
Visit this link for the reference guide: http://php.net/manual/en/book.ctype.php 请访问此链接以获取参考指南: http : //php.net/manual/zh/book.ctype.php
If you place a caret ( ^
) anywhere inside the group ( []
) except the very first character it's treated as ordinary char. 如果将插入符号( ^
)放在组( []
)内的任何位置,但第一个字符除外,则将其视为普通字符。 So, your first regex matches even 因此,您的第一个正则表达式匹配
466^qwe^aa
11123asdasd^aa
aaa^aaa
^^^
Which is not intended I think. 我认为这不是故意的。 Just remove the caret and 0-9
, so your first regex is just [A-Za-z]
. 只需删除插入符号和0-9
,那么您的第一个正则表达式就是[A-Za-z]
。 That mean 'match any character and nothing else '. 那意味着“匹配任何字符,别无其他 ”。
UPDATE Also, as Ben Carey pointed out, the same can be achieved using built-in ctype
extension. 更新另外,正如Ben Carey指出的那样,使用内置的ctype
扩展也可以实现相同的目的。
Unicode properties for letters is \\pL
and for numbers \\pN
字母的Unicode属性为\\pL
,数字的Unicode属性为\\pN
if (preg_match('/^\pL+$/', $pk) return true; // alphabetic
if (preg_match('/^[\pL\pN]+$/', $pk) return false; // alphanumeric
For aphanumeric: 对于字母数字:
function isAlphaNumeric($str) {
return !preg_match('/[^a-z0-9]/i', $str);
}
For alphabetic only: 仅对于字母:
function isAlpha($str) {
return !preg_match('/[^a-z]/i', $str);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.