测试字符串是否等于其中一个字符串(使用正则表达式)


Test if a string is equal to one of the strings (with regex)

如何使用正则表达式完成此操作?

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

我正在尝试:

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

但显然,如果$s包含一个或多个指定的字符串(而不是当它等于其中一个字符串时),这将返回1

您需要

使用开始^和结束$锚点来执行精确的字符串匹配。

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

使用 ^ 和 $ 指定从输入开始到结束的匹配项。

我认为正则表达式对这个问题矫枉过正了。

我的解决方案:

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