Analysis of mathematical operations with PHP

I am working on a project where I need to create a function that will analyze 4 mathematical operations by default (addition, subtraction, multiplication, division). It would be nice if the function could analyze operations between brackets.

Thus, a prerequisite is that the function first checks the operations of multiplication and division (you should check this after it analyzes all the operations between the brackets, if they exist, and this rule should be applied to operations with brackets [the biggest problem is that brackets may contain brackets]). After performing all operations of multiplication and division, he must perform all operations of addition and subtraction. The final number must be returned by functions.

Another nice addition would be the RegExp line, which will check math operations.

Thanks in advance!

+6
source share
6 answers

This should be pretty safe:

function do_maths($expression) { eval('$o = ' . preg_replace('/[^0-9\+\-\*\/\(\)\.]/', '', $expression) . ';'); return $o; } echo do_maths('1+1'); 
+4
source

You can use eval () ( WARNING : make sure you are entering a mathematical operation, and not any other arbitrary input or php code).

 $input = "3 + (4 - 2 * 8) / 2"; eval('$result = ' . $input . ';'); echo "The result is $result"; 
+3
source
+2
source

Regular expressions are not the answer here; I suggest using an expression tree where all terminal nodes are constants or variables, and the other nodes are operators. For example, 2 + 3 * 4 becomes:

 + --- 2 | --- * --- 3 | --- 4 

Then you evaluate the expression using the depth of the first traversal . In PHP, it's hard to imagine trees, but you can use the built-in library as a commentator to suggest or represent them using an associative array of arrays.

0
source

if you want a truly safe math parser then eval will not do this. bcParserPHP can do this. It is implemented in PHP and does not use eval, so it is very safe.

0
source

I can recommend https://github.com/andig/php-shunting-yard , which is a PSR-compatible Shunting Yard algorithm.

0
source

Source: https://habr.com/ru/post/886792/


All Articles