Search code examples
phppreg-match

how to preg_match in php for numeric with fixed range?


how can I preg_match in php for numeric with fixed range?

I want to allow 8 digit number in text box without starting of 0.

Eg-12345678

The following is my piece of code.

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>';
  }
 }
}

Thanks.


Solution

  • Your pattern is just slightly off, and you should be expecting seven digits after the initial digit which is not zero:

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

    Conceptually:

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