Hi,
I need an algorithm to evaluate a boolean expression (within a string) like this:
$validation = "[VALUE] == 'corporation' || [VALUE] == 'family'";
The marker [VALUE] is filled from user input, the strings are configured statically by the developer.
It would be easy to utilize eval() for this but since part of the expression consists of more or less raw user input that would open the application to cross-site-scripting attacks and the like. So that's out of the question.
So, does anybody have any idea (or fully fletched algorithm)
a) that represents an alternative to eval() but does not end up interpreting PHP or
b) for a short (!) custom-built algorithm?
The necessary functionality is:
- comparison of strings as well as numbers
- all string and numeric comparison operators available in PHP
- related expressions via || and &&
- operator precedence via brackets ()
Right now my algorithm goes like this:
1) find all comparisons via preg_match()
2) evaluate all comparisons by parsing the two values and the operator and performing the comparison by-hand through a switch statement.
3) replace comparisons from 1) with boolean results (true|false) from 2)
4) strip anything that is not within (true|false||||&&|(|)) from the string
5) run the string through eval
(sorry, I'm not allowed to post the implementation)
It works and I believe it to be somewhat safe but there has to be something more elegant.
Thanks in advance,
Dominique