This should work for you:
Just add this function to your code:
function calculateBasicMath($expression) {
$expression = preg_replace("/[^0-9\+\-\*\/\.\,]/", "", $expression);
while(preg_match("/(\d+)([\*\/])(\d+)/", $expression, $hM) || preg_match("/(\d+)([\+\-])(\d+)/", $expression, $lM)) {
if(!empty($hM)) {
switch($hM[2]){
case "*":
$expression = str_replace("$hM[1]$hM[2]$hM[3]", $hM[1] * $hM[3], $expression);
break;
case "/":
$expression = str_replace("$hM[1]$hM[2]$hM[3]", $hM[1] / $hM[3], $expression);
break;
}
} elseif(!empty($lM)) {
switch($lM[2]){
case "+":
$expression = str_replace("$lM[1]$lM[2]$lM[3]", $lM[1] + $lM[3], $expression);
break;
case "-":
$expression = str_replace("$lM[1]$lM[2]$lM[3]", $lM[1] - $lM[3], $expression);
break;
}
} else {
break;
}
}
return $expression;
}
And then change your line from:
array_sum(array_column(array_intersect_key($lines, array_flip($keys)), 2));
to:
array_sum(array_map("calculateBasicMath", array_column(array_intersect_key($lines, array_flip($keys)), 2)));
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ See here
So that it basically calls this function for each value.
The function itself first replaces everything expect: [0-9]+-/*.,
with preg_replace()
. Then it simply searches for basic math, e.g. X[+-*/]X
. But where /
and *
has a higher precedence than +
and -
. And as long as it finds such a math expressions it calculates these and replace them.