views:

77

answers:

3

I'm trying to match letters C D F H I E1 E2 CR (case insensitive) and came up with this. It'll match a single letter but wont match the E1 E2 CR. Actually it should. Whats the right way to do this?

preg_match('/^([C]|[D]|[F]|[H]|[I]|[E1]|[E2]|[CR]?)$/','CR')
+6  A: 

[...] 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.

Daniel Vandersluis
+4  A: 

Use:

preg_match('/^(C|D|F|H|I|E1|E2|CR)$/i','CR')
  • A char class with single char like [x] is same as x
  • Use the i modifier to make the matching case insensitive.
codaddict
+6  A: 

Given the fairly limited and specific set of codes you're checking, I'd suggest using

in_array($inputvalue,array('C','D','F','H','I','E1','E2','CR'));

rather than a regex -- it'll run quicker than a regex and be easier to undersand and modify later on.

Spudley
I like the simplicity over regex here. Just be sure to `strtoupper($inputvalue)` first.
brian_d
Thanks for pointng me to the in_array function. Its a lot easier than regex.
Norman