php regular expression to check whether a number consists of 5 digits
php, regex
Solution
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.
Problem
how to write a regular expression to check whether a number is consisting only of 5 digits?