Hi, I'm looking for something that can interpret a string in php and perform simple math calculation, and then return a boolean result as to whether the expression is true or false.
For example:
- Sue types in "3*{mysalary}/9=10000"
- PHP splits this up into two expressions - explode('=',string);
- PHP takes my list of database fields, and replaces any "{}" delimited fields with the data (typecasted to int)
- PHP then evaluates the maths expression
- php then compares the left side to the right side
- boolean result produced.
It may sound complex but it only needs to be very simple. Here are the constraints: 1/ mathematical operators are fixed to: + - / * 2/ comparison operators are fixed to: = > < >= <= 3/ do not need floating point comparisons, everything can be done at an integer level. So any divisions can be rounded if need be or simply just round the final result
There will only ever be two expressions, with one comparison operator. If there is any sort of error at all we will just return false.
Has anyone seen something that can do this already? I know I can make something but why re-invent the wheel right?
If you haven't seen anything do you care to list some "gotcha's" or caveat's that you can think of when building this.
After reading some more I realise I could use the shunting yard algorithm. Does anyone have an implementation of this in PHP?
I am aware the eval could be an easy method to perform this, however, it concerns me that the user could very easily break something using this method or cause syntax errors. I'd rather not include it in the solution, or if i do then it'd need to tightly control how it is used.
Thanks.
Jason