1

だから私は式を文字列として持っています

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

なりたい $comm = $a * 5/100 * (1-2/100);

どうすればphpでこれを行うことができますか?

4

4 に答える 4

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; 
于 2013-02-21T10:39:59.570 に答える
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;
?>
于 2013-02-22T05:04:58.513 に答える