I am looking for a mini scripting language that runs on php, I need to interpret simple formulas (something that a scripting language for a spreadsheet would do). The main thing that I need is Variables and affectation and mathematical operations conditions and if statement.
ex :
if(price1>360) result = (price1 * Q) + price1 * Q /17 else ...
I suggest you take a look at some of the concepts used in a template system like Smarty and implement your own. For instance, the math template allows you to perform operations like this:
{* $height=4, $width=5 *}
{math equation="x + y" x=$height y=$width}
You can just grab the math functions from here, if you want a general guideline of how to create them. There is still a risk of issues since this uses eval()
to do the computations.
In addition, here is a class to evaluate RPN (Reverse Polish Notation) to support the operators: +, - , *, /, IF, THEN, SWAP, DUP, =, <>, >, <. >=
and <=
.
Well, you could also write these little scripts in PHP and execute them using eval. But, since this is like opening Pandora's box, you should really know you can trust the code that is passed, before considering this as a viable option (ie. it's dangerous, really, especially if these formulas are entered by users - I would never use them when users provide the code to be executed).
Another option (probably safer) would be to use some form of javascript interpreter to execute the snippets. There are 2 PHP projects I know of that could be helpful (even though they seem to be in hibernation) : j4p5 and phpjs. If you can install extensions then PECL with SpiderMonkey could be a better option though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With