[...]
defines a character class, which tells the regular expression engine to match one element within the class. For that reason, [E1]
actually means match E or 1. Since you want to match E1
and E2
, you can combine those conditions to E[12]
(ie. E
followed by 1
or 2
). Furthermore, you can simplify all your single letter classes by combining them together. Also, if you add the /i
modifier at the end of your pattern, that will make it case-insensitive.
preg_match('/^([CDFHI]|E[12]|CR)?$/i', 'CR');
Note that the ?
at the end of the pattern makes the preceding group optional. Note that by making part of the pattern optional (as you seem to be trying to do in your question) or the whole pattern optional (like I do in my solution), an empty string will be matched by this pattern.