PHP-解析字符串中的数学方程


PHP - Parse mathematical equations inside strings

我正在努力寻找最好的方法。基本上,我得到的字符串是这样的,任务是打印出经过数学解析的字符串。

杰克通过考试的几率为[0.8*100]%。凯蒂有[(0.25+0.1)*100]%的机会。

数学方程式总是用方括号括起来。我为什么要处理这样的字符串是一个很长的故事,但我真的很感激你的帮助!

PHP有很多数学评估库。一个快速的网络搜索就会发现这个。


编写自己的解析器也是一种选择,如果这只是基本的算术,那么就不应该太难了。有了这些资源,我会远离这件事。


您可以采用更简单的方法并使用eval。请注意首先对您的输入进行消毒。在eval文档的页面上,有一些带有代码的注释。这里有一个例子:

免责声明:我知道eval只是邪恶的拼写错误,这是一件可怕的事情,等等。不过,如果使用得当,它也有用处

<?php
$test = '2+3*pi';
// Remove whitespaces
$test = preg_replace('/'s+/', '', $test);
$number = '(?:'d+(?:[,.]'d+)?|pi|π)'; // What is a number
$functions = '(?:sinh?|cosh?|tanh?|abs|acosh?|asinh?|atanh?|exp|log10|deg2rad|rad2deg|sqrt|ceil|floor|round)'; // Allowed PHP functions
$operators = '[+'/*'^%-]'; // Allowed math operators
$regexp = '/^(('.$number.'|'.$functions.''s*'((?1)+')|'((?1)+'))(?:'.$operators.'(?2))?)+$/'; // Final regexp, heavily using recursive patterns
if (preg_match($regexp, $q))
{
    $test = preg_replace('!pi|π!', 'pi()', $test); // Replace pi with pi function
    eval('$result = '.$test.';');
}
else
{
    $result = false;
}
?>
preg_match_all('/'[(.*?)']/', $string, $out);
foreach ($out[1] as $k => $v)
{
    eval("'$result = $v;");
    $string = str_replace($out[0][$k], $result, $string);
}

如果字符串是用户输入,则此代码是非常危险的,因为它允许执行任何任意代码

从PHP文档示例中更新的eval方法。

<?php
function calc($equation)
{
    // Remove whitespaces
    $equation = preg_replace('/'s+/', '', $equation);
    echo "$equation'n";
    $number = '((?:0|[1-9]'d*)(?:'.'d*)?(?:[eE][+'-]?'d+)?|pi|π)'; // What is a number
    $functions = '(?:sinh?|cosh?|tanh?|acosh?|asinh?|atanh?|exp|log(10)?|deg2rad|rad2deg|sqrt|pow|abs|intval|ceil|floor|round|(mt_)?rand|gmp_fact)'; // Allowed PHP functions
    $operators = '['/*'^'+-,]'; // Allowed math operators
    $regexp = '/^([+-]?('.$number.'|'.$functions.''s*'((?1)+')|'((?1)+'))(?:'.$operators.'(?1))?)+$/'; // Final regexp, heavily using recursive patterns
    if (preg_match($regexp, $equation))
    {
        $equation = preg_replace('!pi|π!', 'pi()', $equation); // Replace pi with pi function
        echo "$equation'n";
        eval('$result = '.$equation.';');
    }
    else
    {
        $result = false;
    }
    return $result;
}
?>

听起来像你的家庭作业。。。。但不管怎样。

你需要使用字符串操作php有很多内置函数,所以你很幸运。请检查explode()函数和str_split()。

以下是专门与字符串相关的函数的完整列表:http://www.w3schools.com/php/php_ref_string.asp

祝你好运。