Checking Number of Digits in Integer

Sometimes you might want to check the digits of an integer, i.e. to validate user input. Here is a really simple way using regular expressions:

# check the number of digits in an integer
$integer = 5721567

# is it between 4 and 6 digits?
$is4to6 = $integer -match '^\d{4,6}$'

# is it exactly 7 digits?
$is7 = $integer -match '^\d{7}$'

# is it at least 4 digits?
$isatleast4 = $integer -match '^\d{4,}$'

"4-6 digits? $is4to6"
"exactly 7 digits? $is7"
"at least 4 digits? $isatleast4"

The examples show how you check for exact matches, or ranges. Note that “^” denotes the beginning and “$” denotes the end of an expression. “\d” represents a digit, and the brace determines how many are allowed.

Twitter This Tip! ReTweet this Tip!