6

How could this be done with regex?

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

I am trying:

 $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).

3 Answers 3

11

You need to use start ^ and end $ anchors to do an exact string match.

$result = preg_match( '/^(aa|bb|cc|dd)$/', $s );
Sign up to request clarification or add additional context in comments.

Comments

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

Use ^ and $ to specify the to match from the beginning of the input till the end.

Comments

3

I think RegEx overkill for this problem.

My solution:

$results = array('aa', 'bb', 'cc', 'dd');
$c = 'aa';

if(in_array($c, $results, true)) {
    echo 'YES';
} else {
    echo 'NO';
}

10 Comments

What it means "overkill" ? I'm not agree with you.
The difference is negligible, you can use whichever you prefer - eval.in/223092
@Styphon, your comparison not equal. eval.in/private/81d6123d2cd184 - eval.in/private/481f2ed8552cb2
@AdilIlhan Run them on the same script, eval.in will not give accurate results if they're on different pages. Each time you run it you will get a different result of up to 0.2s.
Although I am not going to use this approach in this case, +1 for starting another interesting RegEx vs world micro optimisation battle.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.