String to symbols and numbers [duplicate]

2019-09-20 14:54发布

问题:

This question already has an answer here:

  • How to mathematically evaluate a string like “2-1” to produce “1”? 8 answers

Is there a way to turn the addition, subtraction, multiplication, and division symbols in a string to actual addition, subtraction, multiplication, and division symbols, along with the numbers inside the string to actual numbers? So, instead of the symbols acting as part of the string, they would act as they would outside of the string, and same thing for the numbers. Is there a function to do this?

$string = "1+1-1*1/1";

Needed Result:

$result = 1+1-1*1/1 = 1;

回答1:

Assuming you're outputting to the browser,

÷ is ÷

× is ×

and I hope you're able to figure out add and subtract on your own :P

$result = "1 + 1 - 1 × 1 ÷ 1 = 1";