Match multiple letters and letters to numbers

I am trying to match the letters CDFH I E1 E2 CR (case insensitive) and came up with this. It will correspond to one letter, but does not correspond to E1 E2 CR. Actually it should be. What is the right way to do this?

preg_match('/^([C]|[D]|[F]|[H]|[I]|[E1]|[E2]|[CR]?)$/','CR') 
+4
source share
3 answers

Given the rather limited and specific set of codes you are checking, I would suggest using

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

not a regular expression - it will work faster than a regular expression, and will be easier to describe later and change later.

+6
source

[...] defines a character class that tells the regex engine to match one element within the class. For this reason, [E1] actually means matching E or 1. Since you want to match E1 and E2 , you can combine these conditions with E[12] (that is, E followed by 1 or 2 ). In addition, you can simplify all your classes with one letter by combining them together. Also, if you add /i modifier to the end of your pattern, this will make it case insensitive.

 preg_match('/^([CDFHI]|E[12]|CR)?$/i', 'CR'); 

Please note that ? at the end of the template does the previous group optional . Please note that by making part of the template optional (as you seem to be trying to do in your question), or the entire template is optional (for example, I do in my decision), an empty line will correspond to this template.

+6
source

Using:

 preg_match('/^(C|D|F|H|I|E1|E2|CR)$/i','CR') 
  • Char class with one char as [x] matches x
  • Use the i modifier to make the matching case insensitive.
+4
source

All Articles