Check if a string matches one of the strings (with regex)

How can this be done with regex?

return ( $s=='aa' || $s=='bb' || $s=='cc' || $s=='dd' ) ? 1 : 0; 

I'm trying to:

  $s = 'aa'; $result = preg_match( '/(aa|bb|cc|dd)/', $s ); echo $result; // 1 

but obviously this returns 1 if $s contains one or more of the specified strings (not when it is equal to one of them).

+5
source share
3 answers

To do exact string matching you need to use start ^ and end $ .

 $result = preg_match( '/^(aa|bb|cc|dd)$/', $s ); 
+9
source
 $s = 'aa'; $result = preg_match( '/^(aa|bb|cc|dd)$/', $s ); echo $result; 

Use ^ and $ to indicate a match from the beginning of the input to the end.

+3
source

I think RegEx will overwhelm this problem.

My decision:

 $results = array('aa', 'bb', 'cc', 'dd'); $c = 'aa'; if(in_array($c, $results, true)) { echo 'YES'; } else { echo 'NO'; } 
+3
source

Source: https://habr.com/ru/post/1207137/


All Articles