Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP regex digit length only 5 or 9

Tags:

regex

php

I need a regular expression for string validation. String can be empty, can have 5 digits, and can have 9 digits. Other situations is invalid. I am using the next regex:

/\d{5}|\d{9}/

But it doesn't work.

like image 209
Alex Pliutau Avatar asked Jan 27 '11 13:01

Alex Pliutau


2 Answers

Just as Marc B said in the comments, I would use this regular expression:

/^(\d{5}(\d{4})?)?$/

This matches either exactly five digits that might be followed by another four digits (thus nine digits in total) or no characters at all (note the ? quantifier around the digits expression that makes the group optional).

The advantage of this pattern in opposite to the other mentioned patterns with alternations is that this won’t require backtracking if matching five digits failed.

like image 137
Gumbo Avatar answered Oct 05 '22 12:10

Gumbo


use anchors and "?" to allow empty string

/^(\d{5}|\d{9})?$/
like image 24
keymone Avatar answered Oct 05 '22 10:10

keymone