如何将字符串中的数学表达式转换为整数 [英] how to translate math espression in a string to integer

查看:117
本文介绍了如何将字符串中的数学表达式转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一条声明:

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

如何使其等于9?

推荐答案

来自 Richard van Velzen 编写.一旦有了它,并且它匹配,就可以放心,可以在字符串上使用eval了.使用eval之前,请务必确保输入已通过验证!

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.";
}

这篇关于如何将字符串中的数学表达式转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆