<?php /** * @author yusaint * @copyright 2011 */ function cal($expr) { $splittedBy_multi = explode('*', $expr); // (12/3) (2) (12) (12/4) $temp = array(); print_r($splittedBy_multi); foreach ($splittedBy_multi as $k => $v) { $splittedBy_divided = explode('/', $v); if (count($splittedBy_divided) > 1) { $temp[$k] = intval($splittedBy_divided[0]) * intval($splittedBy_divided[0]); foreach ($splittedBy_divided as $val) { $temp[$k] /= intval($val); } } else $temp[$k] = intval($v); } return array_product($temp); } $expr = "10-4+123+100*98*8/100*4*3+3-12/3/4*2*12*12/4+4-8+12/3*12+12"; $splittedBy_plus = explode('+', $expr); //0=>(4*3) 1=>(3-12/3/4*2*12*12/4) 2=>(4-8) $temp = array(); foreach ($splittedBy_plus as $k => $v) { $splittedBy_minus = explode('-', $v); // 3 12/3/4*2*12*12/4 if (count($splittedBy_minus) > 1) //(3) (12/3/4*2*12*12/4) (4) (8) { $temp_minus = array(); foreach ($splittedBy_minus as $key => $value) { $temp_minus[$key] = cal($value); } $minus = 2 * $temp_minus[0]; foreach ($temp_minus as $value) { $minus -= (int)$value; } $temp[$k] = $minus; } else { $temp[$k] = cal($v); } } $sum = 0; foreach ($temp as $value) { $sum += $value; } echo 'the parsed value is:' . $sum."\n"; echo 'the original value is:'.(10-4+123+100*98*8/100*4*3+3-12/3/4*2*12*12/4+4-8+12/3*12+12); ?>