Your regex won't ever match single digit numbers because you're using {2,}
which means match a character 2 or more times.
So let's take a look at this regex here:
#(\d+)\s*([+/*-])\s*(\d+)#
#
: delimiter
(\d+)
: Match a digit one or more times and then group it.
\s*
: Match a space zero or more times
([+/*-])
: Match either +
or -
or *
or /
one time and group it
\s*
: Match a space zero or more times
(\d+)
: Match a digit one or more times and then group it.
#
: delimiter
Let's use some PHP-Fu here and a function I used here:
$input = '2 +2
5*3
6 - 8';
$output = preg_replace_callback('#(\d+)\s*([+/*-])\s*(\d+)#', function($m){
return $m[1].' '.$m[2].' '.$m[3].' = '. mathOp($m[2], (int)$m[1], (int)$m[3]);
}, $input); // You need PHP 5.3+. Anonymous function is being used here !
echo $output;
function mathOp($operator, $n1, $n2){
if(!is_numeric($n1) || !is_numeric($n2)){
return 'Error: You must use numbers';
}
switch($operator){
case '+':
return($n1 + $n2);
case '-':
return($n1 - $n2);
case '*':
return($n1 * $n2);
case '/':
if($n2 == 0){
return 'Error: Division by zero';
}else{
return($n1 / $n2);
}
default:
return 'Unknown Operator detected';
}
}
Output:
2 + 2 = 4
5 * 3 = 15
6 - 8 = -2
Advice:
This will get rather complicated with negative numbers, parenthesis, log and cos/sin functions so you're better off using a parser.