Hello! What about what, and I'm talking about optimization: let's say there is a string "a". "+". "B", where a and b are numbers. QUESTION: how to get the result a + b? Somehow I don’t want to solve it in my forehead, and instead of the "+" sign there can be a lot of things including sqrt (). Maybe there are some options? Thanks to all.
2 answers
How to turn a string into an operator?
In PHP, there is an eval () function for such purposes, but it is not recommended to use it because of the high chances of getting a vulnerability.
For safer use of the eval () function, you must completely trust the data that will be transferred to it for processing. For example, operands can be cast to an integer type (int) , and + - etc. operators can be reduced to + - etc. You can pre-save into an array, and get them only from the array.
Solution example for php> = 7.1 :
$a = 2; $b = 3; $operation = '+'; // Массив с допустимыми операциями $operations = ['+', '-', '*', '/'/*и т.д.*/]; if ( ($k = array_search($operation, $operations)) !== false ) { $op = $operations[$k]; $foo = function (int ...$ints) use($op) { [$a, $b] = $ints; eval("print $a $op $b;"); }; $foo($a, $b); } The result is not difficult to predict: 5
It is safe, but not out of the box, the solution will be to enumerate all possible operators / functions of working with the target operands a and b in your case. Those. if you know the stack of operations, then you can pull them out regularly, as suggested above, and then transfer this case and your operands to a specially trained method. This method using switch...case according to the type of operation will apply one or another calculation logic.
- this is the "in the forehead" to solve the problem - AlexSam
+|-|*|/|%for example by a regular schedule, but what next? You cannot turn them into a valid operator without resorting to dubious functions likeeval(). Therefore, the essence of the issue is not clear. - Edward