3

I'm simply wanting to convert a string which contains an equation into an actual PHP Math Equation, is this possible using PHP5+ ? If so, how?

Here's some examples of which the string may be:

$string = "37-0";
$string = "315+10";
$string = "25+50";
$string = "88-13";

I simply want to parse these into the correct Mathematical answer if that's possible

Curtis Crewe
  • 4,126
  • 5
  • 26
  • 31
  • what's problem it will work – saurav Aug 24 '14 at 07:37
  • The accepted answer to http://stackoverflow.com/questions/12692727/how-to-make-a-calculator-in-php is n excellent ___and safe___ calculator for math equations without any of the problems and dangers of eval – Mark Baker Aug 24 '14 at 10:24

2 Answers2

5

Try this:

$str = '37 - 0';
eval( '$result = (' . $str. ');' );
echo $result;

Check the eval function

Evaluates the given code as PHP.

On a side note:

The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • This solution is the better write up, but I prefer @Valentin Mercier's method (below): it just requires a final semicolon to work. eg. $result = eval("return " . $string . ";"); – Jamie G Oct 17 '19 at 10:46
  • For safety, it would be good to clean the string first, for example $str = preg_replace('/[^0-9+-\/*]+/', '', $str); – n-dru Apr 21 '22 at 09:21
1

You are looking for the PHP function eval

Use it like this:

$string = "88-13";
$result = eval("return " . $string);
Valentin Mercier
  • 5,256
  • 3
  • 26
  • 50