Code explanation of the formula for string formatting in PHP using eval

Source: Internet
Author: User
Sometimes we have a commission formula for each product, and the formula for calculating the Commission is in the form of a string, and when we use this formula, he is not like we wrote: $a =2+3*5; so it's simple to calculate the result, and it's a string, so We have to translate the string into the results we can handle.

Sometimes we have a commission formula for each product, and the formula for calculating the Commission is in the form of a string, and when we use this formula, he does not write as we do: $a =2+3*5; So simple as to calculate the result, And it's a string. So, we have to translate the string into the result we can handle.
The eval () function in PHP can handle PHP code, so this can be used to solve: A calculation formula stored in a string format

Like what:

$str = ' 3+12 '; $result =eval ("return $str;"); echo $result;

Will output: 30

Is the value of an expression

Where the return $str in eval () is the PHP code

The value of the variable can also be brought in:

$a =3; $b =12; $str = ' ($a + $b) '; $result =eval ("return $str;"); echo $result;

Will output: 30

This implementation of the PHP implementation of the calculator code, mainly using the PHP eval function.

Related articles:

A small function that inserts a string at the specified position in a string

PHP Custom intercept Chinese string-utf8 version

PHP Development Tips (10)-the implementation method of Chinese character string interception without garbled characters

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.