Search code examples
phpregexpreg-replace-callback

Replace string within parenthesis with column data


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


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.