0

I'm try to calculate numbers inside string Example:

<?php
$str = '6 + 12 - ( 2 * 3 )';
$results = some_function($str);
Echo $results;
// outputs 12 
?>

Can someone help me with this?

1 Answers1

0

You can accomplish this via the eval function (it runs a string as if it were PHP).

<?php

function some_function($str) {
    eval("return " . $str . ";");
}

$str = '6 + 12 - ( 2 * 3 )';
$results = some_function($str);
echo $results;


?>
Neil
  • 13,713
  • 3
  • 27
  • 50
  • 1
    Please note that you should *avoid* using this method. Look for instance at [**this**](http://stackoverflow.com/questions/18880772/calculate-math-expression-from-a-string-using-eval) question for other methods to solve this. Or the duplication questions, especially the second one shows some really good answers. – Nytrix Apr 07 '17 at 19:02
  • [**Here**](http://stackoverflow.com/a/12693539/5120280), an answer that does all of this. – Nytrix Apr 07 '17 at 19:14