我想从字符串中计算数学表达式.我已经读过,解决方法是使用eval().但是当我尝试运行以下代码时:
<?php
$ma ="2+10";
$p = eval($ma);
print $p;
?>
Run Code Online (Sandbox Code Playgroud)
它给了我以下错误:
解析错误:语法错误,意外的$ end在C:\ xampp\htdocs\eclipseWorkspaceWebDev\MandatoryHandinSite\tester.php(4):eval()'代码在第1行
有人知道这个问题的解决方案.
Roc*_*mat 48
虽然我不建议使用eval它(它不是解决方案),但问题是eval需要完整的代码行,而不仅仅是片段.
$ma ="2+10";
$p = eval('return '.$ma.';');
print $p;
Run Code Online (Sandbox Code Playgroud)
应该做你想做的.
更好的解决方案是为数学表达式编写tokenizer/parser.这是一个非常简单的基于正则表达式的例子,给你一个例子:
$ma = "2+10";
if(preg_match('/(\d+)(?:\s*)([\+\-\*\/])(?:\s*)(\d+)/', $ma, $matches) !== FALSE){
$operator = $matches[2];
switch($operator){
case '+':
$p = $matches[1] + $matches[3];
break;
case '-':
$p = $matches[1] - $matches[3];
break;
case '*':
$p = $matches[1] * $matches[3];
break;
case '/':
$p = $matches[1] / $matches[3];
break;
}
echo $p;
}
Run Code Online (Sandbox Code Playgroud)
cla*_*rkk 32
看看这个..
我在会计系统中使用它,你可以在数量输入字段中编写数学表达式.
$Cal = new Field_calculate();
$result = $Cal->calculate('5+7'); // 12
$result = $Cal->calculate('(5+9)*5'); // 70
$result = $Cal->calculate('(10.2+0.5*(2-0.4))*2+(2.1*4)'); // 30.4
Run Code Online (Sandbox Code Playgroud)
class Field_calculate {
const PATTERN = '/(?:\-?\d+(?:\.?\d+)?[\+\-\*\/])+\-?\d+(?:\.?\d+)?/';
const PARENTHESIS_DEPTH = 10;
public function calculate($input){
if(strpos($input, '+') != null || strpos($input, '-') != null || strpos($input, '/') != null || strpos($input, '*') != null){
// Remove white spaces and invalid math chars
$input = str_replace(',', '.', $input);
$input = preg_replace('[^0-9\.\+\-\*\/\(\)]', '', $input);
// Calculate each of the parenthesis from the top
$i = 0;
while(strpos($input, '(') || strpos($input, ')')){
$input = preg_replace_callback('/\(([^\(\)]+)\)/', 'self::callback', $input);
$i++;
if($i > self::PARENTHESIS_DEPTH){
break;
}
}
// Calculate the result
if(preg_match(self::PATTERN, $input, $match)){
return $this->compute($match[0]);
}
// To handle the special case of expressions surrounded by global parenthesis like "(1+1)"
if(is_numeric($input)){
return $input;
}
return 0;
}
return $input;
}
private function compute($input){
$compute = create_function('', 'return '.$input.';');
return 0 + $compute();
}
private function callback($input){
if(is_numeric($input[1])){
return $input[1];
}
elseif(preg_match(self::PATTERN, $input[1], $match)){
return $this->compute($match[0]);
}
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
我最近创建了一个提供math_eval帮助函数的 PHP 包。它完全可以满足您的需要,而无需使用可能不安全的eval功能。
您只需传入数学表达式的字符串版本,它就会返回结果。
$two = math_eval('1 + 1');
$three = math_eval('5 - 2');
$ten = math_eval('2 * 5');
$four = math_eval('8 / 2');
Run Code Online (Sandbox Code Playgroud)
您还可以传入变量,如果需要,变量将被替换。
$ten = math_eval('a + b', ['a' => 7, 'b' => 3]);
$fifteen = math_eval('x * y', ['x' => 3, 'y' => 5]);
Run Code Online (Sandbox Code Playgroud)
链接: https: //github.com/langleyfoxall/math_eval
| 归档时间: |
|
| 查看次数: |
54144 次 |
| 最近记录: |