php – Parsing an arithmetic expression in a string


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

You need to break it down into elements and perform the actions that are indicated in the line. I wanted to do it through miltiexplode(array("+","-","*","/"), $string) , but in this case the signs are lost. Probably need to iterate over the elements, but I don't see a good way. Yes, and I have difficulties with strings.


2a*3b matches 2*a*3*b i.e. so explode won't work. here you can dribble towards eval, convert a string to php like and execute 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);  

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

Scroll to Top