PHP如何计算含加减运算符的字符串及数组转串后的数值?
Got it, let's break down how to compute those math expressions in PHP. I'll cover both a quick solution (with important security notes) and a safer, more robust method that works even with untrusted input.
Quick (But Cautious) Solution Using eval()
If you’re 100% sure your input string only contains digits, +, -, and no sketchy code, PHP’s eval() function can directly evaluate the expression for you. Here’s how it works for your examples:
Example 1: Calculate "2+4+3-12+3-5"
$string1 = "2+4+3-12+3-5"; $result1 = eval("return $string1;"); echo $result1; // Output: -5
Example 2: Your Sample String "3+5+3-7+4-3-1"
$string2 = "3+5+3-7+4-3-1"; $result2 = eval("return $string2;"); echo $result2; // Output: 4 (matches your expected result)
Example 3: Converted Array String
Your array [1, '+', 6, '-', 43, '+', 10] becomes "1+6-43+10" when imploded. Let’s compute it:
$array = [1, '+', 6, '-', 43, '+', 10]; $string3 = implode("", $array); $result3 = eval("return $string3;"); echo $result3; // Output: -26
Heads Up: eval() runs any PHP code passed to it. If your input comes from a user or untrusted source, this is a huge security risk—someone could inject malicious code. For those cases, use the safer method below.
Safer Manual Parsing Method
This approach splits the expression into numbers and operators, then calculates the result step by step without relying on eval(). Here’s a reusable function you can use:
function calculateMathString($expression) { // Split the string into numbers (including negatives) and operators preg_match_all('/(-?\d+)|([+-])/', $expression, $matches); // Filter out empty values from the matches $numbers = array_filter($matches[1]); $operators = array_filter($matches[2]); // Start with the first number as our initial result $result = (int)array_shift($numbers); // Loop through each operator and corresponding number to compute the total foreach ($operators as $index => $op) { $currentNumber = (int)$numbers[$index]; if ($op === '+') { $result += $currentNumber; } elseif ($op === '-') { $result -= $currentNumber; } } return $result; }
Test the Function with Your Examples
// Test 1 echo calculateMathString("2+4+3-12+3-5"); // Output: -5 // Test 2 echo calculateMathString("3+5+3-7+4-3-1"); // Output: 4 // Test 3 $array = [1, '+', 6, '-', 43, '+', 10]; $string3 = implode("", $array); echo calculateMathString($string3); // Output: -26
This function uses regex to safely extract only valid numbers and operators, so it’s safe even if the input comes from an untrusted source. No risk of code injection here!
内容的提问来源于stack exchange,提问作者Ehtasham Nasir

