I found out that we can fully make use of preg_match to accomplish the above task:
/** * Function parse_condition * @param string $condition * @return bool */ function parse_condition($condition){ // match {a} {condition} {b} preg_match('/.*(.*?)\s(.*?)\s(.*?)/sU', $condition, $condition_matches); // condition_matches[1] will be a, remove $, () and leading/tailing spaces $a = trim(str_replace(array('$','()'),'',$condition_matches[1])); // condition_matches[2] will be the operator $operator = $condition_matches[2]; // condition_matches[3] will be b, remove $, () and leading/tailing spaces $b = trim(str_replace(array('$','()'),'',$condition_matches[3])); // It is advisable to pass variables into array or a "hive" // but in this example, let's just use global // Make variable's variable $$a accessible global $$a; // And for $$b too global $$b; $cmp1 = isset($$a)?($$a):($a); $cmp2 = isset($$b)?($$b):($b); switch($operator){ case '==': return($cmp1 == $cmp2); break; case '!=': return($cmp1 != $cmp2); break; case '===': return($cmp1 === $cmp2); break; case '!==': return($cmp1 !== $cmp2); break; default: return false; break; } }
so I can use it like this:
// TESTCASES $var_a = 100; $var_b = 100; $var_c = 110; $var_d = (double) 100; if(parse_condition('$var_a == $var_b')){ // TRUE echo 'Yeah I am Good!' . PHP_EOL; } if(parse_condition('$var_a != $var_c')){ // TRUE echo 'Good for this one too!' . PHP_EOL; } if(parse_condition('$var_b == $var_c')){ // FALSE echo 'Yeah I am Good!' . PHP_EOL; }else{ echo 'But I am not with this one :(' . PHP_EOL; } if(parse_condition('$var_a != 110')){ // TRUE echo 'I can compare values too' . PHP_EOL; } if(parse_condition('$var_a === $var_d')){ // FALSE // }else{ echo 'Or even tell the difference between data types' . PHP_EOL; }
eval, but no, please don't.