V
V
Vitaly Zhuk2013-05-29 10:10:30
PHP
Vitaly Zhuk, 2013-05-29 10:10:30

PHP Math Lexer?

Hello to all habrasociety.
Can you please tell me if there is any universal mathematical parser in PHP?
The essence of the problem:
There is a simple string, which contains numbers, functions, operands. For example:
0.85 + 1.15
(2^3 - 200) * 2
abs(-100) + sin(0.75) - 2
2*3*(0.55 + 0.15) / 100
And it is necessary to return the result of executing this line as a mathematical expression.
All these lines will be stored in the database, and as a result, the idea arose to find (write) a mathematical parser.
There are also some wishes:
1. Implementation of variables.

$mathParser = new MathParser(':a * :b');
$mathParser
  ->setVariable('a', 0.25)
  ->setVariable('b', 0.35);

$result = $mathParser->getResult();

2. Implementation of own functions.
$mathParser = new MathParser('my_func(:a)');
$mathParser
  ->setVariable('a', $myVariable)
  ->addFunction('my_func', function($a) { return abs($a); } );

$result = $mathParser->getResult();

3. Good control of syntax errors (To check before execution/saving).
UPDATE:
Recommended to see:
1. github.com/SymDevStudio/MathExecutor

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
AxisPod, 2013-05-29
@AxisPod

Well, take MathExecutor, it is very simple, you can easily add your own functions.
I implemented my own (but in C ++) something in a couple of days, in fact, Reverse Polish Notation is very easy to process, and converting a regular notation to OPV is nothing complicated, the algorithms are all described on the internet.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question