-1

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;
jessica
  • 1,667
  • 1
  • 17
  • 35

1 Answers1

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";

I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116
  • Just found this similar question to mine: http://stackoverflow.com/questions/5057320/php-function-to-evaluate-string-like-2-1-as-arithmetic-2-1-1 which got like 14 upvotes. Just wondering, what's so different about mine that it gets downvotes. – jessica Sep 30 '15 at 00:25
  • well, it's not the same question, but also, that one's been acquiring upvotes from randos searching google for half a decade. anyway, I +1'd. If this is the answer you're looking for please hit the checkmark. – I wrestled a bear once. Sep 30 '15 at 00:28
  • I've already found the answer in the old question, but I'll upvote and check yours, anyway. :) – jessica Sep 30 '15 at 00:30
  • yeah, after re-reading your question it occurs to me that you're looking for `eval()`, probably for homework, but in the real world, you should steer clear of eval. – I wrestled a bear once. Sep 30 '15 at 00:35
  • yeah, you're better off googling to get better examples, but suppose you're getting the numbers from a form posted over http, the user could easily inject code to to, say, delete your entire file structure for example. like i said, this is an over-simplification and you should hit up google if you're really curious. – I wrestled a bear once. Sep 30 '15 at 00:40
  • Yeah...but that has nothing to do with eval() itself. You're suppose to clean all user input in the first place, before you do anything with them. – jessica Sep 30 '15 at 00:45
  • the thing is, it's not like sql where there are special dedicated functions to escape (or bind) parameters. there is no one-size-fits-all solution for escaping user-input to be used in eval. For simple math stuff you can just validate that it's a single number, but what if you were using strings instead of numbers, it can become very difficult to properly verify that the string is not executable code. – I wrestled a bear once. Sep 30 '15 at 00:52