how to translate math espression in a string to in

2019-08-28 02:03发布

For example I have a statement:

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

How to make it to be equal 9 ?

标签: php math eval
4条回答
闹够了就滚
2楼-- · 2019-08-28 02:51

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.";
}
查看更多
Rolldiameter
3楼-- · 2019-08-28 02:51

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.

查看更多
Summer. ? 凉城
4楼-- · 2019-08-28 02:52
$string_with_expression = '2+2';
eval('$eval_result = ' . $string_with_expression)`;

$eval_result - is what you need.

查看更多
叼着烟拽天下
5楼-- · 2019-08-28 03:05

There is intval function

But you can't apply direct to $var

For parser Check this Answer

查看更多
登录 后发表回答