how to translate math espression in a string to integer

我的未来我决定 提交于 2019-12-25 03:56:17

问题


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



来源:https://stackoverflow.com/questions/8164168/how-to-translate-math-espression-in-a-string-to-integer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!