Описание класса: Этот класс работает с вложенными в строку символами данных, например «[(((2 * 4) + 6))]», чтобы вырвать правильные математические вычисления. Пример, конечно, сложнее - в этом отношении - я сам не понимаю этот класс... Он просто работает так, как ожидалось!
Основная проблема (частная функция) находится здесь:
Код: Выделить всё
private function compute($input){
$compute = create_function('', 'return '.$input.';');
return 0 + $compute();
}
Код: Выделить всё
// Calculate the result
if(preg_match(self::PATTERN, $input, $match)){
return $this->compute($match[0]);
}
Код: Выделить всё
class Field_calculate {
const PATTERN = '/(?:\-?\d+(?:\.?\d+)?[\+\-\*\/])+\-?\d+(?:\.?\d+)?/';
const PARENTHESIS_DEPTH = 10;
public function calculate($input){
if(strpos($input, '+') != null || strpos($input, '-') != null || strpos($input, '/') != null || strpos($input, '*') != null){
// Remove white spaces and invalid math chars
$original = $input ;
//$GLOBALS['A_INFO'] .= "Clean input : ".$original." = ".$input."
";
// Validate parenthesis
$nestled = $this->analyse($input);
if(!$nestled){
$GLOBALS['A_INFO'] .= "_x_Parentheses in ".$original." NOT NESTLED CORRECTLY
";
}
$input = str_replace(',', '.', $input);
$input = preg_replace('/[^0-9\.\+\-\*\/\(\)]/', '', $input);
if($input[0] == '(' && $input[strlen($input) - 1] == ')') {
$input = substr($input, 1, -1);
}
// Calculate each of the parenthesis from the top
$i = 0;
while(strpos($input, '(') || strpos($input, ')')){
$input = preg_replace_callback('/\(([^\(\)]+)\)/', 'self::callback', $input);
$i++;
if($i > self::PARENTHESIS_DEPTH){
break;
}
}
// Calculate the result
if(preg_match(self::PATTERN, $input, $match)){
return $this->compute($match[0]);
}
return 0;
}
return $input;
}
private function analyse($input){
$depth = 0;
for ($i = 0; $i < strlen($input); $i++) {
$depth += $input[$i] == '(';
$depth -= $input[$i] == ')';
if ($depth < 0) break;
}
if ($depth != 0) return false;
else return true;
}
private function compute($input){
$compute = create_function('', 'return '.$input.';');
return 0 + $compute();
}
private function callback($input){
if(is_numeric($input[1])){
return $input[1];
}
elseif(preg_match(self::PATTERN, $input[1], $match)){
return $this->compute($match[0]);
}
return 0;
}
}
Подробнее здесь: https://stackoverflow.com/questions/630 ... ithin-a-ca
Мобильная версия