Search code examples
phpmathevaluser-input

Alternatives to eval() for doing math equations using php


Are there alternative to using eval() for doing math equations, or is there some way to safety use eval with user inputs?

$string = "1+2-3*4/5";
$answer = eval($answer = $string);

Solution

  • Perhaps you may want to only select the mathematical and numericals from the given string, then do the eval.

    preg_match_all("/[0-9()+\-*\/.]/", $string, $output_array);
    $operation = implode("", $output_array[0]);
    eval($operation);