【问题标题】:Replace string within parenthesis with column data用列数据替换括号内的字符串
【发布时间】:2013-04-19 01:14:32
【问题描述】:

我已经编写了一些代码来允许对特定的数据列进行计算。

例如 {1}*{2} 将导致第 1 列乘以第 2 列。我需要做的是将这些数字替换为该列的实际值。

简单地说,我需要能够获取括号内的值,然后像 $column["value from parenthesis"] 一样使用它来获取要插入到计算中的值。

然后我可以评估字符串。

提前致谢

【问题讨论】:

  • {1}*{2} 在哪里?只是在某个地方的字符串中?另外,你有没有尝试过?
  • 您最好将输入拆分为对于每个通过结果数组并使用 {} 引用您的列,例如 $column[$array[0]],我认为您必须对其进行正则表达式

标签: php regex preg-replace-callback


【解决方案1】:

这样的事情应该可以工作:

$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";

当使用未定义的索引时,可能希望给出更严重的错误,但本质上这应该通过一些调整来工作。

此外,如果您运行的 PHP 版本早于 5.4,则需要重写短数组语法和 lambda。

【讨论】:

    【解决方案2】:

    PHP 摇滚!!!

    $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.

    【讨论】:

      猜你喜欢
      • 2014-08-14
      • 2015-04-16
      • 1970-01-01
      • 2019-07-31
      • 2014-03-09
      • 1970-01-01
      • 2018-11-28
      • 2013-02-08
      • 1970-01-01
      相关资源
      最近更新 更多