doutonghang2761 2017-02-21 21:46
浏览 44

PHP:如何在没有eval()的情况下解析模板表达式

I have a complex object with both objects and arrays. It's too large to post the data object here (defined as $this->data in my class). I also have a configuration file with simple "{{name.something}}" template expressions. I'm trying to write a simple expression parser to parse the configuration strings, such as "{{patient.firstname}}".

Example Expressions:

{{patient.firstname}}, {{patient->firstname}} or even {{patient.customfields[0].customfieldvalue}}

The code below seems to work well. Now that I've got it working, I'm questioning the usage and safety of the eval() function. The config file does not include any user entered data. Is this code safe? Is there a way to re-write this without eval()?

<?php
// Note - This is only part of the class.

/*
 * Parse Template Value Expressions
 * Allows complex object data to be used. Examples:
 * {{patient.firstname}}, {{patient->firstname}} or even {{patient.customfields[0].customfieldvalue}}
 */
private function _parseDataValue($value = '') {

    // Parse Template Expressions: Allows data input to be used {{name}}, {{name1.name2}}, etc
    if ($value != '' && preg_match('/\{\{([a-z0-9\-_\[\]\>\.]+)\}\}/i', trim($value))) {
        $value = preg_replace_callback('/\{\{([a-z0-9\-_\[\]\>\.]+)\}\}/i', 
                array(&$this, '_buildDataCallback'), trim($value));
    }
    return $value;
}

/*
 * Parse Template Value Expressions Callback Method
 */
private function _buildDataCallback($matches) {

    $out = '';
    if (isset($matches[1])) {
        $var = $matches[1];
        @eval("\$out = \$this->data->$var;");
    }
    return $out;
}

?>
  • 写回答

1条回答 默认 最新

  • draxq02664 2017-02-21 21:56
    关注

    You can use curly braces to get an object's property with a variable name.

    (PHP dynamic name for object property)

    I think this would replace your usage of eval():

     <?php
      $out = $this->data->{$var};
    
    评论

报告相同问题?

悬赏问题

  • ¥50 comsol稳态求解器 找不到解,奇异矩阵有1个空方程返回的解不收敛。没有返回所有参数步长;pid控制
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功