how to translate math espression in a string to in

2019-08-28 02:16发布

问题:

For example I have a statement:

$var = '2*2-3+8'; //variable type is string

How to make it to be equal 9 ?

回答1:

From this page, a very awesome (simple) calculation validation regular expression, written by Richard van Velzen. Once you have that, and it matches, you can rest assured that you can use eval over the string. Always make sure the input is validated before using eval!

<?php
$regex = '{
    \A        # the absolute beginning of the string
    \h*        # optional horizontal whitespace
    (        # start of group 1 (this is called recursively)
    (?:
        \(        # literal (

        \h*
        [-+]?        # optionally prefixed by + or -
        \h*

        # A number
        (?: \d* \. \d+ | \d+ \. \d* | \d+) (?: [eE] [+-]? \d+ )?

        (?:
            \h*
            [-+*/]        # an operator
            \h*
            (?1)        # recursive call to the first pattern.
        )?

        \h*
        \)        # closing )

        |        # or: just one number

        \h*
        [-+]?
        \h*

        (?: \d* \. \d+ | \d+ \. \d* | \d+) (?: [eE] [+-]? \d+ )?
    )

    # and the rest, of course.
    (?:
        \h*
        [-+*/]
        \h*
        (?1)
    )?
    )
    \h*

    \z        # the absolute ending of the string.
}x';

$var = '2*2-3+8';

if( 0 !== preg_match( $regex, $var ) ) {
    $answer = eval( 'return ' . $var . ';' );
    echo $answer;
}
else {
    echo "Invalid calculation.";
}


回答2:

What you have to do is find or write a parser function that can properly read equations and actually calculate the outcome. In a lot of languages this can be implemented by use of a Stack, you should have to look at things like postfix and infix parsers and the like.

Hope this helps.



回答3:

$string_with_expression = '2+2';
eval('$eval_result = ' . $string_with_expression)`;

$eval_result - is what you need.



回答4:

There is intval function

But you can't apply direct to $var

For parser Check this Answer



标签: php math eval