为了扩展 dethtron5000 的答案,我想到这样做以防止出现异常复杂的正则表达式的一种方法是让开发人员将他的条件分解成更多的多维条件事物并使用递归函数对其进行循环。在每个级别,您都会有一个“运算符”,它可以是“AND”或“OR”(至少我希望这被称为“运算符”,如果不能随意更改它)。
在您的示例中,您有:(32 < 40 AND 10 > 5 OR 20 == 10)
(看起来您正在对条件进行 json_encoding,所以我从以下 PHP 数组开始,然后从那里向后工作。我假设您可以通过json_decode
您的开发人员提供的内容来获得有效的 PHP 数组)。上面的示例将表示为以下 PHP 数组:
$arr = array(
'required' => 'conditional',
'conditions' => array(
'requirements' => array(
'operator' => 'OR', // this makes it so that if any conditions at this level are true, it returns true
0 => array(
'operator' => 'AND', // this makes it so that all the conditions at this sub-level need to be satisfied to return true
array(
'conditional1' => 32,
'conditional2' => 40,
'operation' => 'lessthan',
),
array(
'conditional1' => 10,
'conditional2' => 5,
'operation' => 'greaterthan',
),
),
1 => array(
// Since there is only one condition here, it is not necessary to specify "AND" or "OR"
array(
'conditional1' => 20,
'conditional2' => 10,
'operation' => 'equals',
),
),
),
),
);
然后,您可以使用如下递归函数遍历条件:
function check_req(Array $reqs) {
$operator = (isset($reqs['operator'])) ? $reqs['operator'] : 'AND';
unset($reqs['operator']);
foreach ($reqs as $req) {
if (isset($req['operation'])) {
switch ($req['operation']) {
case 'lessthan':
$valids[] = $req['conditional1'] < $req['conditional2'];
break;
case 'greaterthan':
$valids[] = $req['conditional1'] > $req['conditional2'];
break;
case 'equals':
$valids[] = $req['conditional1'] == $req['conditional2'];
break;
}
}
else {
$valids[] = check_req($req);
}
}
if ($operator == 'OR') {
foreach ($valids as $valid) {
if ($valid == true) {
return true;
}
}
return false;
}
else {
foreach ($valids as $valid) {
if ($valid == false) {
return false;
}
}
return true;
}
}
var_dump(check_req($arr['conditions']['requirements'])); // true in this case
当我对其进行 json_encode 编码时,我得到:
{
"required":"conditional",
"conditions":{
"requirements":{
"operator":"OR",
"0":{
"operator":"AND",
"0":{
"conditional1":32,
"conditional2":40,
"operation":"lessthan"
},
"1":{
"conditional1":10,
"conditional2":5,
"operation":"greaterthan"
}
},
"1":[{
"conditional1":20,
"conditional2":10,
"operation":"equals"
}]
}
}
}
我假设这是开发人员必须为您提供的。