首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何检查一个数字是否以两个允许的数字php开头?

如何检查一个数字是否以两个允许的数字php开头?
EN

Stack Overflow用户
提问于 2020-10-21 03:54:18
回答 4查看 946关注 0票数 0

如何验证数字字符串仅以下列允许的列表启动前两个数字:

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.

代码语言:javascript
运行
复制
$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中的上述数字必须从列表中的前两个数字开始,这样才能继续。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2020-10-21 04:11:18

另一种方法是将数字临时转换为字符串,并使用^([01]\d|2[0-4]|30)的正则表达式检查数字字符串是否以上面提到的特定值开头。您可以使用PHP的函数来帮助检查字符串是否与正则表达式匹配。

所以你的代码变成:

代码语言:javascript
运行
复制
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:匹配000102,.,1011,…,19
  • 2[0-4]:匹配2021,.,24
  • 30:匹配30
  • ([01]\d|2[0-4]|30):匹配[01]\d2[0-4]30

如果正则表达式模式匹配成功,preg_match函数将返回1

票数 1
EN

Stack Overflow用户

发布于 2020-10-21 04:02:35

如果您允许的起始数字存储在一个数组中,则可以使用$number使用substr()in_array()中提取第二个数字,然后使用in_array()进行检查。

票数 0
EN

Stack Overflow用户

发布于 2020-10-21 04:09:43

您可以为此使用正则表达式,但要注意:以0开头的数字将被解释为octal并转换为基数10。为了避免这种情况,必须引用数字:

代码语言:javascript
运行
复制
$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之间(因为它必须以两位数开始)。

功能参考:

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64456440

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档