php计算字符串中的公式

时间:2013-02-21 10:12:19

标签: php formula equation

所以我将公式作为字符串

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

我希望它是$comm = $a * 5/100 * (1-2/100);

我怎么能在php中做到这一点?

4 个答案:

答案 0 :(得分:3)

要以正确的方式,从头开始可靠,安全地执行此操作,您需要执行以下操作:

  1. 词法分析,这涉及将输入与令牌进行模式匹配:

    (a x 5% - 2%)
    

    会变成类似下面的代币链:

    openparen variable multiply integer percent minus integer percent closeparen
    
  2. 语法分析,这包括获取这些令牌并定义它们之间的关系,类似这样,匹配令牌的模式:

    statement = operand operator statement
    
  3. 然后,您需要解析生成的语法树,以便运行它并产生答案。

  4. 它永远不会像$comm = $a * 5/100 - 2/100;那样简单,但它会产生相同的结论。

    某个人已经可能已经解决了这个问题,这是我在一次简短的谷歌搜索后发现的两个问题: PHP Maths Expression ParserAnd another

    这些SO问题与Smart design of a math parser?Process mathematical equations in php

    类似

答案 1 :(得分:2)

看看

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

哪个可以评估数学代码

 // 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)'));

发现于: Process mathematical equations in php

答案 2 :(得分:1)

它只是尝试,但也许是一个好的开始。

$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; 

答案 3 :(得分:0)

解决!!

<?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;
?>