【问题标题】:how to preg_match in php for numeric with fixed range?如何在 php 中为具有固定范围的数字进行 preg_match?
【发布时间】:2020-02-07 12:10:12
【问题描述】:

如何在 php 中 preg_match 为固定范围的数字?

我想在文本框中允许不以 0 开头的 8 位数字。

例如-12345678

以下是我的一段代码。

if(isset($_POST['submit1'])) {
    if(empty($_POST["phone"]))
 {
  $error .= '<p><label class="text-danger">Please Enter your phone number</label></p>';
 }
 else{
     if(!preg_match("/^[1-9][0-9]{8}$/",$PhNum))
  {
   $error .= '<p><label class="text-danger">Only 8 digit numbers are allowed</label></p>';
  }
 }
}

谢谢。

【问题讨论】:

    标签: php preg-match


    【解决方案1】:

    您的模式只是稍微偏离了一点,您应该期待在初始数字之后的 七个 数字,而不是零:

    if (!preg_match("/^[1-9][0-9]{7}$/", $PhNum)) {
        $error .= '<p><label class="text-danger">Only 8 digit numbers are allowed</label></p>';
    }
    

    概念上:

    [1-9][0-9]{7}  <-- seven digits, for a total of 8 digits
    ^^^ one digit
    

    【讨论】:

    • 谢谢先生,但仍然不正确。当我输入 12345678 或 1234567 时,它仍然显示“只允许 8 位数字”。如果我输入 12345678 不应该显示消息,对吗?
    猜你喜欢
    • 2014-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    • 2012-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多