Question

I need a pattern that verifies the input field is in the following format.

1st char: a, b, c, or d
2nd: 0-9
third: 0-9
4th: 0-9 (optional char)

valid example: a939, c321, d11, c32
invalid: aa939, c1

preg_match('/^[DSFP][0-9]/', $data) // doesn't work :(
Was it helpful?

Solution

Your regex should be:

/^[abcd]\d{2,3}$/i

Explanation:

^       -- matches line start
[abcd]  -- matches one of literal characters a, b, c, d
\d{2,3} -- matches 2 or 3 digits
$       -- matches line end

OTHER TIPS

Just try with following regex:

/^[a-d][0-9]{2,3}$/

Explanation:

[a-d]      - allows letters from `a` to `d`
[0-9]      - allows just one digit - so invalid here
[0-9]{2,3} - allows 2 to 3 digits
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top