PHP - Solving Equations that include a ternary operator without eval()?

253 Views Asked by At

I'm currently working on a PHP application that needs to solve equations that may, or may not, have a ternary operator.

For example, after replacing my variables in the equation, we are left with the following string:

$eq = '(3.07 > 10 ? 1.93 * 10 : 3.07 * 1.93)';

We were previously using eval() (which would obviously work), but moved to an EOS package from PHP Classes (https://www.phpclasses.org/package/2055-PHP-Solve-equations-with-multiple-variables.html) because of the security issues with eval().

The EOS class doesn't interpret the ternary operator, and I don't want to go back to eval(), so what are my options here? Is there a better PHP EOS library that I can use somewhere?

1

There are 1 best solutions below

2
Don't Panic On

Assuming there's just one ternary, you could break up the string into the separate parts of the ternary expression and evaluate the parts separately.

$eq = '3.07 > 10 ? 1.93 * 10 : 3.07 * 1.93';

preg_match('/(.+)\?(.+):(.+)/', $eq, $parts);

if (isset($parts[3])) {
  $result = Parser::solve($parts[1]) ? Parser::solve($parts[2]) : Parser::solve($parts[3]);
} else {
  $result = Parser::solve($eq);
}

If there's more than one ternary, you could probably still could do it if you were better at regex than me. :)

I admit this approach is a bit naive, I can think of various things that would break it pretty easily, e.g. a parenthetical ternary sub-expression, but it could work for simple examples like the one in your question.