php calculate formula in string [duplicate]

微笑、不失礼 提交于 2019-12-01 13:20:00

问题


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?


回答1:


To do this the right way, reliably and safely, from scratch, you will need to perform:

  1. Lexical analysis, this involves pattern matching the input with tokens:

    (a x 5% - 2%)
    

    would become something like the following chain of tokens:

    openparen variable multiply integer percent minus integer percent closeparen
    
  2. Syntax analysis, this involves taking those tokens and defining the relationships between them, something like this, matching up the patterns of tokens:

    statement = operand operator statement
    
  3. 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




回答2:


Take a look at

http://www.phpclasses.org/package/2695-PHP-Safely-evaluate-mathematical-expressions.html

Which can evaluate Math Code

 // instantiate a new EvalMath
  $m = new EvalMath;
  $m->suppress_errors = true;
 // set the value of x
  $m->evaluate('x = 3');
   var_dump($m->evaluate('y = (x > 5)'));

Found at: Process mathematical equations in php




回答3:


It just trying, but maybe good start.

$somm = 0;
$a = 30;

$str = "(a x 5% - 2%)";

$pt1 = "/x/i";
$str = preg_replace($pt1, "*", $str);

$pt2 = "/([a-z])+/i";
$str = preg_replace($pt2, "\$$0", $str);

$pt3 = "/([0-9])+%/";
$str = preg_replace($pt3, "($0/100)", $str);

$pt4 = "/%/";
$str = preg_replace($pt4, "", $str);

$e = "\$comm = $str;";
eval($e);
echo $e . "<br>";
echo $comm; 



回答4:


Solved!!

<?php 
    function evalmath($equation)
    {
        $result = 0;
        // sanitize imput
        $equation = preg_replace("/[^a-z0-9+\-.*\/()%]/","",$equation);
        // convert alphabet to $variabel 
        $equation = preg_replace("/([a-z])+/i", "\$$0", $equation); 
        // convert percentages to decimal
        $equation = preg_replace("/([+-])([0-9]{1})(%)/","*(1\$1.0\$2)",$equation);
        $equation = preg_replace("/([+-])([0-9]+)(%)/","*(1\$1.\$2)",$equation);
        $equation = preg_replace("/([0-9]{1})(%)/",".0\$1",$equation);
        $equation = preg_replace("/([0-9]+)(%)/",".\$1",$equation);
        /*if ( $equation != "" ){
            $result = @eval("return " . $equation . ";" );
        }
        if ($result == null) {
            throw new Exception("Unable to calculate equation");
        }
        return $result;*/
        return $equation;
    }
    $total = 18000;
    $equation =  evalmath('total-(230000*5%-2%+3000*2*1)');
    if ( $equation != "" ){

        $result = @eval("return " . $equation . ";" );
    }
    if ($result == null) {

        throw new Exception("Unable to calculate equation");
    }
    echo $result;
?>


来源:https://stackoverflow.com/questions/14999578/php-calculate-formula-in-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!