Make PHP account in the order that is in the string

4

I need an order of calculation that is in the string to be done in the order that is in it. For example:

$string = '(10*10)+(30-5)/2';

I need PHP to interpret this not as a string , but rather as a calculation and do according to what has to be done. How can I do this?

    
asked by anonymous 08.09.2016 / 03:00

3 answers

6

You can do this:

$string = '(10*10)+(30-5)/2';
eval( '$result = (' . $string. ');' );
echo $result;

Obs: As you should know the division comes before the sum, then the result will be: 112.5

If you want the split to occur last. Add one more parenthesis to your equation. See: ((10 * 10) + (30-5)) / 2

    
08.09.2016 / 03:09
8

I have decided to give a complementary answer on the eval() which is a valid solution. This can be seen at Is Eval a Good Guy or a Bandit? .

To tell you the truth, any information about eval() that does not have this caveat for me borders on being wrong.

Using eval() is very dangerous. You can even use it without taking big risks, but almost nobody knows how to do it, so it's best not to try before you're sure you understand all the risks and know how to solve them. It's so complicated to make sure that it's often better to use a more complex form than it.

The question does not clarify where this information comes from. If it comes from a client, then forget the eval() , the job to ensure security in it is so great that making the simple formula compiler for what it needs is simpler. Maybe I can even do it with RegEx , which I do not like, but it's a solution. The solution goes through a .

If the information does not come externally, then it is likely to be safe, though, why would you use eval() on something that does not come externally? There may be a motive, but it is unlikely to be the right mechanism. I've seen a lot of people using such a feature, for lazy to enter codes . This is a very wrong motive.

    
08.09.2016 / 13:50
3

As a complement to the answer already given, I decided to post a solution that I have on the subject.

There is a Symfony component called Expression Language , which can make your service easier. With it you can use simple expressions, through strings , which will be interpreted by a parser and get the result in php.

See:

use Symfony\Component\ExpressionLanguage\ExpressionLanguage;

$language = new ExpressionLanguage();

var_dump($language->evaluate('1 + 2')); // displays 3

var_dump($language->compile('1 + 2')); // displays (1 + 2)

I'm not sure, but it seems to me that the syntax interpreted by this library is very similar to that of Twig .

Nothing against the response of eval , but as said by @bigown , it's good to know what you're doing, not to put your application at risk.

    
08.09.2016 / 14:05