<?php
function calculate_string( $mathString ) {
$mathString = trim($mathString); // trim white spaces
$mathString = preg_replace('#[^0-9\+\-\*\/\(\) ]#', '', $mathString); // remove any non-numbers chars; exception for math operators
var_dump($mathString);
$compute = create_function("", "return (" . $mathString . ");" );
return 0 + $compute();
}
$string = " (1 + 1) * (2 + 2)";
echo calculate_string($string); // outputs 8
- Output for 8.0.0 - 8.0.30, 8.1.0 - 8.1.27, 8.2.0 - 8.2.17, 8.3.0 - 8.3.4
- string(17) "(1 + 1) * (2 + 2)"
Fatal error: Uncaught Error: Call to undefined function create_function() in /in/MX8XM:6
Stack trace:
#0 /in/MX8XM(11): calculate_string('(1 + 1) * (2 + ...')
#1 {main}
thrown in /in/MX8XM on line 6
Process exited with code 255. - Output for 7.2.0 - 7.2.33, 7.3.0 - 7.3.31, 7.4.0 - 7.4.33
- string(17) "(1 + 1) * (2 + 2)"
Deprecated: Function create_function() is deprecated in /in/MX8XM on line 6
8
- Output for 5.4.2 - 5.4.45, 5.5.24 - 5.5.35, 5.6.7 - 5.6.28, 7.0.0 - 7.0.20, 7.1.0 - 7.1.33, 7.3.32 - 7.3.33
- string(17) "(1 + 1) * (2 + 2)"
8
preferences:
232.04 ms | 402 KiB | 267 Q