This question already has an answer here:
So I have formula as string
$comm = "(a x 5% - 2%)";
I want it to be $comm = $a * 5/100 * (1-2/100);
How can I do this in php?
This question already has an answer here:
So I have formula as string
$comm = "(a x 5% - 2%)";
I want it to be $comm = $a * 5/100 * (1-2/100);
How can I do this in php?
Take a look at
http://www.phpclasses.org/package/2695-PHP-Safely-evaluate-mathematical-expressions.html
Which can evaluate Math Code
Found at: Process mathematical equations in php
To do this the right way, reliably and safely, from scratch, you will need to perform:
Lexical analysis, this involves pattern matching the input with tokens:
would become something like the following chain of tokens:
Syntax analysis, this involves taking those tokens and defining the relationships between them, something like this, matching up the patterns of tokens:
Then you will need to parse the resulting syntax tree so that you can run it and produce the answer.
It won't ever look as simple as
$comm = $a * 5/100 - 2/100;
but it will result in the same conclusion.Someone somewhere has already likely had a go at this problem, here's two I found after a brief Google search: PHP Maths Expression Parser, And another.
These SO questions are similar as well Smart design of a math parser?, Process mathematical equations in php
Solved!!
It just trying, but maybe good start.