
本文详细介绍了如何在php环境中,不依赖`eval()`函数,安全有效地计算包含四则运算和括号的数学表达式。通过讲解调度场算法(shunting-yard algorithm)将中缀表达式转换为逆波兰表示法(rpn),并进一步实现rpn表达式的求值过程,从而提供一个健壮且可控的表达式计算解决方案。
在Web开发或任何需要动态计算表达式的场景中,直接使用eval()函数来执行用户提供的数学表达式存在显著的安全风险和性能问题。eval()函数能够执行任意PHP代码,一旦用户输入包含恶意代码,可能导致服务器被攻击。为了规避这些风险,并实现一个更安全、可控的表达式计算器,我们可以采用基于调度场算法(Shunting-yard Algorithm)的方法。
要实现不依赖eval()的表达式计算器,我们需要理解以下几个核心概念:
调度场算法将中缀表达式的每个字符逐一处理,并根据其类型(操作数、运算符、括号)执行不同的操作:
当所有字符处理完毕后,将操作符栈中剩余的所有运算符依次弹出并添加到输出队列。最终,输出队列中的元素序列就是逆波兰表示法。
立即学习“PHP免费学习笔记(深入)”;
我们将通过一系列PHP函数来实现这个表达式计算器。
首先,定义一些辅助函数来判断字符类型和读取数字:
<?php
/**
* 判断字符是否为运算符
* @param string $char 待判断字符
* @return bool
*/
function is_operator($char) {
static $operators = array('+', '-', '/', '*', '%');
return in_array($char, $operators);
}
/**
* 判断字符是否为数字或小数点
* @param string $char 待判断字符
* @return bool
*/
function is_number($char) {
return (($char == '.') || ($char >= '0' && $char <= '9'));
}
/**
* 从字符串中读取完整的数字
* @param string $string 原始字符串
* @param int $i 当前索引(引用传递)
* @return string 读取到的数字字符串
*/
function readnumber($string, &$i) {
$number = '';
while ($i < strlen($string) && is_number($string{$i})) {
$number .= $string{$i};
$i++;
}
// 返回前将 $i 减去1,因为外部循环会再次 $i++
// 或者在外部循环中处理 $i 的递增
// 这里的实现是让外部循环直接使用 readnumber 返回的长度来更新 $i
return $number;
}
?>这个函数实现了调度场算法的核心逻辑。
<?php
/**
* 将中缀表达式转换为逆波兰表示法 (RPN)
* @param string $mathexp 中缀数学表达式
* @return array RPN表示的元素数组
*/
function mathexp_to_rpn($mathexp) {
// 定义运算符优先级
$precedence = array(
'(' => 0, // 括号优先级最低,用于栈内比较
'-' => 3,
'+' => 3,
'*' => 6,
'/' => 6,
'%' => 6
);
$i = 0;
$final_stack = array(); // 最终输出队列 (RPN)
$operator_stack = array(); // 操作符栈
while ($i < strlen($mathexp)) {
$char = $mathexp{$i};
// 1. 处理数字
if (is_number($char)) {
$num = readnumber($mathexp, $i);
array_push($final_stack, (float)$num); // 将数字转换为浮点数并推入输出队列
// readnumber 已经更新了 $i,这里需要减去1,因为外层循环还会 $i++
// 或者调整 readnumber 的返回逻辑,使其返回数字长度
// 原始代码中 readnumber 返回的是数字本身,然后通过 strlen($num) 来更新 $i
$i += (strlen($num) - 1); // 减去1是因为循环末尾会再次 $i++
$i++; // 这里的 $i++ 是为了跳过当前字符,已经在 readnumber 内部处理,所以这里需要调整
continue;
}
// 2. 处理运算符
if (is_operator($char)) {
// 循环弹出栈顶优先级更高或同级的运算符到输出队列
while (
!empty($operator_stack) &&
end($operator_stack) != '(' &&
$precedence[$char] <= $precedence[end($operator_stack)]
) {
array_push($final_stack, array_pop($operator_stack));
}
array_push($operator_stack, $char); // 当前运算符入栈
$i++;
continue;
}
// 3. 处理左括号
if ($char == '(') {
array_push($operator_stack, $char);
$i++;
continue;
}
// 4. 处理右括号
if ($char == ')') {
// 不断弹出操作符栈中的运算符到输出队列,直到遇到左括号
while (!empty($operator_stack) && end($operator_stack) != '(') {
array_push($final_stack, array_pop($operator_stack));
}
array_pop($operator_stack); // 弹出左括号(不添加到输出队列)
$i++;
continue;
}
// 忽略空格或其他未知字符
$i++;
}
// 表达式处理完毕,将操作符栈中剩余的所有运算符弹出到输出队列
while ($oper = array_pop($operator_stack)) {
array_push($final_stack, $oper);
}
return $final_stack;
}
?>注意: 在readnumber和mathexp_to_rpn的$i递增逻辑上,原始代码有些许不一致,这里已根据常见实现方式进行了调整,确保$i能正确跳过已处理的字符。readnumber内部已经递增$i直到数字结束,所以外部调用后,$i已经指向数字后的第一个字符。mathexp_to_rpn中的$i += (strlen($num) - 1);以及随后的$i++;需要修正为仅$i += strlen($num);。为了保持与原始意图一致,我将readnumber的$i参数改为传值,并在mathexp_to_rpn中通过strlen($num)来更新$i。
修正后的readnumber和mathexp_to_rpn部分:
<?php
// ... (is_operator, is_number 保持不变) ...
/**
* 从字符串中读取完整的数字
* @param string $string 原始字符串
* @param int $startIndex 读取开始的索引
* @return array 包含读取到的数字字符串和新索引的数组
*/
function readnumber($string, $startIndex) {
$number = '';
$currentIndex = $startIndex;
while ($currentIndex < strlen($string) && is_number($string{$currentIndex})) {
$number .= $string{$currentIndex};
$currentIndex++;
}
return ['value' => $number, 'newIndex' => $currentIndex];
}
/**
* 将中缀表达式转换为逆波兰表示法 (RPN)
* @param string $mathexp 中缀数学表达式
* @return array RPN表示的元素数组
*/
function mathexp_to_rpn($mathexp) {
$precedence = array(
'(' => 0,
'-' => 3,
'+' => 3,
'*' => 6,
'/' => 6,
'%' => 6
);
$i = 0;
$final_stack = array();
$operator_stack = array();
while ($i < strlen($mathexp)) {
$char = $mathexp{$i};
if (is_number($char)) {
$num_info = readnumber($mathexp, $i);
array_push($final_stack, (float)$num_info['value']);
$i = $num_info['newIndex']; // 更新索引到数字之后
continue;
}
if (is_operator($char)) {
while (
!empty($operator_stack) &&
end($operator_stack) != '(' &&
$precedence[$char] <= $precedence[end($operator_stack)]
) {
array_push($final_stack, array_pop($operator_stack));
}
array_push($operator_stack, $char);
$i++;
continue;
}
if ($char == '(') {
array_push($operator_stack, $char);
$i++;
continue;
}
if ($char == ')') {
while (!empty($operator_stack) && end($operator_stack) != '(') {
array_push($final_stack, array_pop($operator_stack));
}
if (!empty($operator_stack) && end($operator_stack) == '(') {
array_pop($operator_stack); // 弹出左括号
}
$i++;
continue;
}
// 忽略空格等其他字符
$i++;
}
while ($oper = array_pop($operator_stack)) {
array_push($final_stack, $oper);
}
return $final_stack;
}
?>RPN表达式的求值过程相对简单:遍历RPN序列,遇到操作数则入栈,遇到运算符则从栈中弹出两个操作数进行运算,并将结果重新入栈。
<?php
/**
* 计算逆波兰表示法 (RPN) 表达式的结果
* @param array $rpnexp RPN表示的元素数组
* @return float 表达式计算结果
*/
function calculate_rpn($rpnexp) {
$stack = array(); // 操作数栈
foreach($rpnexp as $item) {
if (is_operator($item)) {
// 弹出两个操作数
$j = array_pop($stack);
$i = array_pop($stack);
// 根据运算符执行计算并将结果入栈
switch ($item) {
case '+': array_push($stack, $i + $j); break;
case '-': array_push($stack, $i - $j); break;
case '*': array_push($stack, $i * $j); break;
case '/':
if ($j == 0) {
throw new InvalidArgumentException("Division by zero.");
}
array_push($stack, $i / $j);
break;
case '%': array_push($stack, $i % $j); break;
}
} else {
// 操作数直接入栈
array_push($stack, $item);
}
}
return $stack[0]; // 最终栈中只剩一个结果
}
?>这是一个包装函数,它首先将中缀表达式转换为RPN,然后计算RPN表达式的结果。
<?php
/**
* 计算中缀数学表达式的结果
* @param string $exp 中缀数学表达式
* @return float 表达式计算结果
*/
function calculate($exp) {
return calculate_rpn(mathexp_to_rpn($exp));
}
?>将上述所有函数整合到一个文件中:
<?php
/**
* 判断字符是否为运算符
* @param string $char 待判断字符
* @return bool
*/
function is_operator($char) {
static $operators = array('+', '-', '/', '*', '%');
return in_array($char, $operators);
}
/**
* 判断字符是否为数字或小数点
* @param string $char 待判断字符
* @return bool
*/
function is_number($char) {
return (($char == '.') || ($char >= '0' && $char <= '9'));
}
/**
* 从字符串中读取完整的数字
* @param string $string 原始字符串
* @param int $startIndex 读取开始的索引
* @return array 包含读取到的数字字符串和新索引的数组
*/
function readnumber($string, $startIndex) {
$number = '';
$currentIndex = $startIndex;
while ($currentIndex < strlen($string) && is_number($string{$currentIndex})) {
$number .= $string{$currentIndex};
$currentIndex++;
}
return ['value' => $number, 'newIndex' => $currentIndex];
}
/**
* 将中缀表达式转换为逆波兰表示法 (RPN)
* @param string $mathexp 中缀数学表达式
* @return array RPN表示的元素数组
*/
function mathexp_to_rpn($mathexp) {
$precedence = array(
'(' => 0,
'-' => 3,
'+' => 3,
'*' => 6,
'/' => 6,
'%' => 6
);
$i = 0;
$final_stack = array();
$operator_stack = array();
while ($i < strlen($mathexp)) {
$char = $mathexp{$i};
if (is_number($char)) {
$num_info = readnumber($mathexp, $i);
array_push($final_stack, (float)$num_info['value']);
$i = $num_info['newIndex'];
continue;
}
if (is_operator($char)) {
while (
!empty($operator_stack) &&
end($operator_stack) != '(' &&
$precedence[$char] <= $precedence[end($operator_stack)]
) {
array_push($final_stack, array_pop($operator_stack));
}
array_push($operator_stack, $char);
$i++;
continue;
}
if ($char == '(') {
array_push($operator_stack, $char);
$i++;
continue;
}
if ($char == ')') {
while (!empty($operator_stack) && end($operator_stack) != '(') {
array_push($final_stack, array_pop($operator_stack));
}
if (!empty($operator_stack) && end($operator_stack) == '(') {
array_pop($operator_stack); // 弹出左括号
} else {
// 括号不匹配错误处理
throw new InvalidArgumentException("Mismatched parentheses.");
}
$i++;
continue;
}
// 忽略空格或其他未知字符
$i++;
}
while ($oper = array_pop($operator_stack)) {
if ($oper == '(') {
throw new InvalidArgumentException("Mismatched parentheses."); // 栈中仍有左括号,说明不匹配
}
array_push($final_stack, $oper);
}
return $final_stack;
}
/**
* 计算逆波兰表示法 (RPN) 表达式的结果
* @param array $rpnexp RPN表示的元素数组
* @return float 表达式计算结果
*/
function calculate_rpn($rpnexp) {
$stack = array();
foreach($rpnexp as $item) {
if (is_operator($item)) {
if (count($stack) < 2) {
throw new InvalidArgumentException("Invalid RPN expression: not enough operands for operator " . $item);
}
$j = array_pop($stack);
$i = array_pop($stack);
switch ($item) {
case '+': array_push($stack, $i + $j); break;
case '-': array_push($stack, $i - $j); break;
case '*': array_push($stack, $i * $j); break;
case '/':
if ($j == 0) {
throw new InvalidArgumentException("Division by zero.");
}
array_push($stack, $i / $j);
break;
case '%': array_push($stack, $i % $j); break;
}
} else {
array_push($stack, $item);
}
}
if (count($stack) != 1) {
throw new InvalidArgumentException("Invalid RPN expression: too many operands or operators.");
}
return $stack[0];
}
/**
* 计算中缀数学表达式的结果
* @param string $exp 中缀数学表达式
* @return float 表达式计算结果
*/
function calculate($exp) {
try {
return calculate_rpn(mathexp_to_rpn($exp));
} catch (InvalidArgumentException $e) {
echo "Error: " . $e->getMessage() . "\n";
return NAN; // 或者其他错误指示
}
}
// 示例使用
$expression = "27+38+81+48*33*53+91*53+82*14+96";
echo "表达式: " . $expression . " = " . calculate($expression) . "\n"; // 预期输出 90165
$expression2 = "(10 + 20) * 3 / 2 - 5";
echo "表达式: " . $expression2 . " = " . calculate($expression2) . "\n"; // 预期输出 40
$expression3 = "10 / 3";
echo "表达式: " . $expression3 . " = " . calculate($expression3) . "\n"; // 预期输出 3.333...
$expression4 = "5 + (2 * 3"; // 括号不匹配
echo "表达式: " . $expression4 . " = " . calculate($expression4) . "\n";
$expression5 = "10 / 0"; // 除以零
echo "表达式: " . $expression5 . " = " . calculate($expression5) . "\n";
?>以上就是PHP中不使用eval()安全计算数学表达式:基于调度场算法的实现的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号