There is a format string 2a*3b+100 and 2 numbers a and b .

It is necessary to break it into elements and perform the actions that are specified in the line I wanted to do it through miltiexplode(array("+","-","*","/"), $string) , but in this case the signs are lost. Probably, you need to sort through the elements, but I do not see a good way. Yes, and I experience difficulties with strings.

  • 2
    This task is not solved in the forehead without the finished library; it is on the trees or on the stack, depending on how you will parse. There is likely to require not only bust, but also recursion. The easiest way to start is algolist.manual.ru/syntax/parsear.php - cheops

1 answer 1

2a*3b corresponds to 2*a*3*b ie therefore, explode is not a ride. here you can skip to the side of eval to bring the line to php like and for example

 $formualPHP = '$a='.$youNamberA.';'; // это $a=2; $formualPHP .= '$b='.$youNamberB.';'; // это $b=3; $formulaPHP .= 'return '.str_replace(array('a','b'),array('*$a','*$b'),$formula); // $a=2;$b=3; return 2*$a*3*$b+100; $result = eval($formulaPHP); var_dump($result); 

But you have to be careful with eval () if the numbers can be custom, i.e. taken from get, post and etc. sources.

  • Someone slapped a minus and did not unsubscribe - Naumov