user3472449
user3472449

Reputation: 59

Evaluate mathematical operations inside a string using PHP

I want to evaluate a mathematical operations inside the string after I get it in that string. Here is the string

$string = "Add this two numbers [4+2+2]. And [5*3/2] will result to?"

I already get those numbers:

$f_number = "4+2+2";
$s_number = "5*3/2";

How can I evaluate this automatically using any function? Sample:

echo anyfunction($f_number);//will result to 8
echo anyfunction($s_number);//will result to 7.5

because if I will echo directly it will just output like this:

echo $f_number;//will result to 4+2+2
echo a$s_number;//will result to 5*3/2

Upvotes: 0

Views: 2941

Answers (1)

GolezTrol
GolezTrol

Reputation: 116100

You can use eval. It's probably the easiest way out. Mind though that it can also be used for other expressions, because it basically executes any PHP code that is in the string.

But by wrapping it in a function, like you intended, you can at least black box it, and add safety measures later if you need to, or even switch to a different expression evaluator, without having to change all your code.

A simple safety measure would be to check if the string only contains numeric values, whitespace and allowed operators. That way it should be impossible to secretly inject actual code.

function anyfunction($expr)
{
  // Optional: check if $expr contains only numerics and operators

  // actual evaluation. The code in $expre should contain a return 
  // statement if you want it to return something.
  return eval("return $expr;");
}

echo anyfunction($f_number);

Upvotes: 0

Related Questions