如何将字符串中的数学表达式转换为整数

rsk*_*k82 0 php math eval

例如,我有一个声明:

$var = '2*2-3+8'; //variable type is string
Run Code Online (Sandbox Code Playgroud)

如何使它平等9

Ber*_*rak 7

这个页面,一个非常棒的(简单的)计算验证正则表达式,由Richard van Velzen编写.一旦你拥有它,并且匹配,你可以放心,你可以在字符串上使用eval.在使用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.";
}
Run Code Online (Sandbox Code Playgroud)