Question

I have written some code to allow calculations to be done on specific columns of data.

For example {1}*{2} would result in column 1 being multiplied by column 2. What I need to be able to do is replace these numbers with the actual values of the column.

Putting it simply I need to be able to get the value within the parenthesis, then use it like $column["value from parenthesis"] to get the value to insert into the calculation.

I can then evaluate the string.

Thanks in advance

Was it helpful?

Solution

Something like this should work:

$myString = '{1}*{2}';
$myValues = [1 => '684', 2 => '42'];
$myFormula = preg_replace_callback('{([0-9]+)}', function($match) use ($myValues) {
  return $myValues[$match] ?: 'undefined';
}, $myString);
echo "Resulting formula: $myFormula";

Might want to give a harder error when an undefined index is used, but essentially this should work with some tweaking.

Also if you run a older PHP version than 5.4 you would need to rewrite the short array syntax and the lambda.

OTHER TIPS

PHP Rocks !!!

$string = 'blabla bla I want this to be done !!! {10} + {12} Ah the result is awesome but let\'s try something else {32} *    {54}';

// Requires PHP 5.3+
$string = preg_replace_callback('/\{(\d+(\.\d+)?)\}\s*([\+\*\/-])\s*\{(\d+(\.\d+)?)\}/', function($m){
return mathOp($m[3], $m[1], $m[4]);
}, $string);

echo $string; // blabla bla I want this to be done !!! 22 Ah the result is awesome but let's try something else 1728

// function from: http://stackoverflow.com/a/15434232
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';
    }
}

Online demo.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top