Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mini scripting language on top of php

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 ...

like image 940
Ayoub M. Avatar asked Oct 11 '22 02:10

Ayoub M.


2 Answers

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 <= .

like image 128
Kelly Avatar answered Oct 14 '22 19:10

Kelly


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.

like image 36
wimvds Avatar answered Oct 14 '22 20:10

wimvds