Reputation: 27855
how to write a regular expression to check whether a number is consisting only of 5 digits?
Upvotes: 4
Views: 19592
Reputation: 2291
Although not using regexp, but hopefully faster:
$var = trim($var);
if(strlen($var) == 5 && ctype_digit($var))
{
//
}
EDIT: Added trim function. It's important! It removes spaces so that strlen() function works as expected. Also it makes sure $var is a STRING. You need to pass a string to ctype_digit. If you pass say, an integer it will return false!!!
Upvotes: 4
Reputation: 95344
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.
Upvotes: 22
Reputation: 91028
This regex will make sure the number does not start with zeros:
if(preg_match('/^[1-9]\d{4}$/', $number))
echo "Number is 5 digits\n";
else
echo "Number is not five digits\n";
But why not use is_numeric()
instead?
if(is_numeric($number) && $number >= 10000 && $number <= 99999)
echo "Number is 5 digits\n";
else
echo "Number is not five digits\n";
Or you can even just cast it to an integer to make sure it only has an integer value:
if(strval(intval($number)) === "$number" && $number >= 10000 && $number <= 99999)
echo "Number is 5 digits\n";
else
echo "Number is not five digits\n";
Upvotes: 14
Reputation: 655269
Try this:
^[0-9]{5}$
The ^
and $
mark the begin and end of the string where the characters described by [0-9]
must be repeated 5 times. So this only matches numbers with exactly 5 digits (but it can still be 00000
). If you want to allow only numbers from 10000 to 99999:
^[1-9][0-9]{4}$
And if you want to allow any number up to 5 digits (0 to 99999):
^(?:0|[1-9][0-9]{0,4})$
The (?:
expr
)
is just a non-capturing grouping used for the alternation between zero and the other numbers with a non-zero leading digit.
Upvotes: 7