0

let's say we have a string like:

"23+sqrt(53)*7"

Is there any way to convert this to a number and print the result of it?

Ivar
  • 6,138
  • 12
  • 49
  • 61
Mehdi
  • 181
  • 1
  • 1
  • 10
  • 1
    Mehdi, please note the comment I added to the answer. Don't just blindly use `eval()`, _escpecially_ when you allow users to input/change the formula. – Ivar Feb 11 '21 at 16:25
  • @Ivar , yes yes. thank you for reminding that to me. I'm going to use regex to make it accept only the inputs including only arithmetic functions. is there any other way to safeguard it? – Mehdi Feb 11 '21 at 16:37
  • 1
    A good regular expression should be safe. You can also check out the solutions used in [this post](https://stackoverflow.com/questions/1015242/how-to-evaluate-formula-passed-as-string-in-php). (Also linked at the top of your question.) – Ivar Feb 11 '21 at 16:41
  • @Ivar yes I checked that out. thank you again – Mehdi Feb 11 '21 at 16:44

1 Answers1

0
$string = "23+sqrt(53)*7";
$number = eval('return ' . $string . ';');

echo $number;
spzout
  • 104
  • 3
  • 1
    Please note that `eval` can be _very_ dangerous and a big security risk. https://stackoverflow.com/questions/951373/when-is-eval-evil-in-php – Ivar Feb 11 '21 at 16:23