Parse math operations with PHP

前端 未结 6 1888
执笔经年
执笔经年 2020-12-01 22:14

I am working on a project where I need to make a function that will parse the 4 default math operations (addition, subtraction, multiplication, division). It would be nice i

相关标签:
6条回答
  • 2020-12-01 22:56

    You could use eval() (WARNING: be sure what enters is a math operation and not some other arbitrary input or php code).

    $input = "3 + (4 - 2 * 8) / 2";
    
    eval('$result = ' . $input . ';');
    
    echo "The result is $result";
    
    0 讨论(0)
  • 2020-12-01 22:58

    if you want a truly safe math parser, then eval won't do it. bcParserPHP can do it. It is implemented in PHP and does not use eval, thus it is very secure.

    0 讨论(0)
  • 2020-12-01 23:00

    This should be pretty secure:

    function do_maths($expression) {
      eval('$o = ' . preg_replace('/[^0-9\+\-\*\/\(\)\.]/', '', $expression) . ';');
      return $o;
    }
    
    echo do_maths('1+1');
    
    0 讨论(0)
  • 2020-12-01 23:05

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

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

    Then, you evaluate the expression by using a depth-first traversal. In PHP it's sort of difficult to represent trees, but you could either use a built-in library as a commenter suggested or represent them using an associative array of arrays.

    0 讨论(0)
  • 2020-12-01 23:12

    there was a similar problem
    How to evaluate formula passed as string in PHP? you can try to use Class: Eval Math from php classes http://www.phpclasses.org/package/2695-PHP-Safely-evaluate-mathematical-expressions.html

    0 讨论(0)
  • 2020-12-01 23:12

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

    0 讨论(0)
提交回复
热议问题