(php/Laravel) How do I calculate mathematical expressions?

Asked

Viewed 694 times

0

  • This is it: do the mathematical calculation from the already composed string: "3 + 2 = 5"

1 answer

1

I leave here a way without using eval(), for this already has an answer that was made longer ago whose @Bacco put the link on top of the question:

function callback1($m) {return c($m[1]);}
function callback2($n,$m) {
    $o=$m[0];
    $m[0]=' ';
    return $o=='+' ? $n+$m : ($o=='-' ? $n-$m : ($o=='*' ? $n*$m : $n/$m));
}
function c($s){ 
    while ($s != ($t = preg_replace_callback('/\(([^()]*)\)/','callback1',$s))) $s=$t;
        preg_match_all('![-+/*].*?[\d.]+!', "+$s", $m);
        return array_reduce($m[0], 'callback2');
}

$str = '(3 + 2) * 5';
echo c($str);

DEMONSTRATION

Source: Excellent response withdrawn from here

  • 1

    I don’t even think it’s appropriate :)

  • If Eval() is the answer, you are asking the wrong question. - Rasmus Lerdorf

  • @Miguel as indicated in his links, a small parser. It takes more work than a simple Time to implement, but ensures a future peace that is priceless :)

  • I do not disagree and I am not in favor of the use of Eval, if taking care with the data in the input may work well, but what I recommend is to search if the question is not duplicate, always check when it is dup http://answall.com/a/134015/3635

  • The calculation does not match using this method.

  • What’s the odds? @Rafael

  • Like this: $calculus = "(89*12)*14-17/2"; Eval('echo '.$calculus.';'); The result has to give: 14943.5. I had to put in a regular expression so I could use it that way.

  • I’ll see, 2 mins

  • I noticed @Rafael, the problem is that this function does not respect the laws of mathematics, first multiplication/division and only then sum/subtraction. Excuse ):

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.