I want to use PHP to calculate simple algebraic expressions like, 8*(5+1)
, entered via an tag by a normal user (which means,
There is a Math Parser class called bcParserPHP that might be of interest.
Seems fairly simple to use and pretty powerful.
Example code from their site:
$parser = new MathParser();
$parser->setVariable('X', 5);
$parser->setVariable('Y', 2);
$parser->setExpression('COS(X)+SIN(Y)/2');
echo $parser->getValue();
Unfortunately, it's a commercial product; I don't know if that would stop you using it or not (guess it depends on the price and on your needs).
A non-commercial alternative might be this one: http://www.phpclasses.org/package/2695-PHP-Safely-evaluate-mathematical-expressions.html
Note that this class uses eval()
internally, which I would avoid doing if possible.
Failing that, writing your own language parser would be the ideal solution, but not really sensible to do that in PHP.