Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php regular expression to check whether a number consists of 5 digits

Tags:

regex

php

how to write a regular expression to check whether a number is consisting only of 5 digits?

like image 939
coderex Avatar asked Nov 27 '22 22:11

coderex


1 Answers

This regular expression should work nicely:

/^\d{5}$/

This will check if a string consists of only 5 numbers.

  • / is the delimiter. It is at the beginning and the end of a regular expression. (User-defined, you can use any character as delimiter).

  • ^ is a start of string anchor.

  • \d is a shorthand for [0-9], which is a character class matching only digits.

  • {5} means repeat the last group or character 5 times.

  • $ is the end of string anchor.

  • / is the closing delimiter.


If you want to make sure that the number doesn't start with 0, you can use the following variant:

/^[1-9]\d{4}$/

Where:

  • / is the delimiter. It is at the beginning and the end of a regular expression. (User-defined, you can use any character as delimiter).

  • ^ is a start of string anchor.

  • [1-9] is a character class matching digits ranging from 1 to 9.

  • \d is a shorthand for [0-9], which is a character class matching only digits.

  • {4} means repeat the last group or character 4 times.

  • $ is the end of string anchor.

  • / is the closing delimiter.


Note that using regular expressions for this kind of validation is far from being ideal.

like image 113
Andrew Moore Avatar answered Dec 09 '22 19:12

Andrew Moore