如何在php中对具有固定范围的数字进行preg_match?

问题描述 投票:0回答:1

我如何在php中进行preg_match以获取具有固定范围的数字?

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

例如-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个回答
0
投票

您的模式刚好稍微偏离,并且您应该期望在起始数字(不为零的数字)之后的七个数字:

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
© www.soinside.com 2019 - 2024. All rights reserved.