1

I am trying to write a math equation with PHP

$text = "value1 * 2";

$txt = str_replace('value1','500',$text);

when echo $txt; // (500 * 2)

i want replace and equation and when echo // 1000

thanks and regrades

  • It is string, you can use [`eval()`](http://php.net/manual/en/function.eval.php) to run it as code but is not good idea – Mohammad Sep 24 '18 at 09:29
  • Also use https://stackoverflow.com/questions/18880772/calculate-math-expression-from-a-string-using-eval – Mohammad Sep 24 '18 at 09:31

2 Answers2

0

Why don't you just use a variable with the value instead of using str_replace()? It's way more readable and it's the correct way to do mathematical operations.

Like this:

$value1 = 500; 
$txt = $value1 * 2; 

Note that this way the value you use in $value1 could also be "500" because when doing $value1 * 2 php converts it to a number

LukeSavefrogs
  • 528
  • 6
  • 15
0

Maybe by using explode and list

$text = "value1 * 2";
$txt = str_replace('value1','500',$text);
list($string1, $string2) = explode("*", $txt);
echo $string1*$string2;
Aroon
  • 991
  • 2
  • 15
  • 34