如何验证数字字符串仅以下列允许的列表启动前两个数字:
01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, and 30.
$number = 1234567890;
if(ctype_digit($number)){
    if (strlen($number) <= 10) {
        echo "The registered number is correct";
    } else {
        echo "The number must have 10 digits";
    }
} else {
    echo "Number must be digit / numeric only.";
}我想在此功能中添加的是验证存储在$number中的上述数字必须从列表中的前两个数字开始,这样才能继续。
发布于 2020-10-21 04:11:18
另一种方法是将数字临时转换为字符串,并使用^([01]\d|2[0-4]|30)的正则表达式检查数字字符串是否以上面提到的特定值开头。您可以使用PHP的函数来帮助检查字符串是否与正则表达式匹配。
所以你的代码变成:
if(ctype_digit($number)){
   if (strlen($number) <= 10 and preg_match('/^([01]\d|2[0-4]|30)/', (string)$number)) {
       echo "The registered number is correct";
   } else {
       echo "The number must have 10 digits or it begins with incorrect values";
   }
} else {
   echo "Number must be digit / numeric only.";
}正则表达式解释:
^:匹配字符串开头的模式[01]\d:匹配00,01,02,.,10,11,…,192[0-4]:匹配20,21,.,2430:匹配30([01]\d|2[0-4]|30):匹配[01]\d、2[0-4]或30如果正则表达式模式匹配成功,preg_match函数将返回1。
发布于 2020-10-21 04:02:35
如果您允许的起始数字存储在一个数组中,则可以使用$number使用substr()从in_array()中提取第二个数字,然后使用in_array()进行检查。
发布于 2020-10-21 04:09:43
您可以为此使用正则表达式,但要注意:以0开头的数字将被解释为octal并转换为基数10。为了避免这种情况,必须引用数字:
$number = '055231';
// Fill the list of allowed numbers
$allowed = array_map(function($number) { 
    // Fill each element to length 2 with '0' to the left
    return str_pad($number, 2, '0', STR_PAD_LEFT); 
}, range(1, 24));
$allowed[] = 30;
if (preg_match('/^\d{2,10}$/', $number)) {
    // At this point we know it contains only numbers
    // Extract first two characters
    $start = substr($number, 0, 2);
   
    // Check if it's in the allowed list
    if (in_array($start, $allowed)) {
        echo "The registered number is correct";
    } else {
        echo "The number is incorrect";
    }
} else {
    echo "Number must be digit / numeric only.";
}Regex细分:
^和$是分隔符。字符串必须完全匹配。\d。数字字符类。只匹配号码。{2,10}。前一个组的长度必须在2到10之间(因为它必须以两位数开始)。功能参考:
https://stackoverflow.com/questions/64456440
复制相似问题