【问题标题】:How to parse a variable inside a string inside a CodeIgniter view?如何在 CodeIgniter 视图中解析字符串中的变量?
【发布时间】:2013-04-13 21:14:13
【问题描述】:

我有一个名为 get_variable 的函数,它从数据库中获取变量的值。

假设我的变量(存储在数据库中)的值类似于:“我喜欢 $fruit”

我想将这个字符串(将 $fruit 转换为正确的值)传递给我的视图。

我有以下设置(下面的伪代码):

$details['fruit'] = 'apples';
$details['test'] = get_variable('my_variable_name');

$var = $CI->load->view('viewname',$details,TRUE);

问题是在我看来 ($var) 输出的是“我喜欢 $fruit”

我想要的是“我喜欢苹果”

我觉得我在这里错过了一步,也许是可变变量? (http://php.net/manual/en/language.variables.variable.php),但不知道如何让它发挥作用。任何见解将不胜感激。

【问题讨论】:

  • 你能发布你的视图代码吗?

标签: php codeigniter templates variable-assignment


【解决方案1】:

如果您确定数据库中的变量是安全的(只有您可以更改它们),您可以像这样评估 get 变量函数中的代码:

function get_variable($var, $data = array())
{
  // Here the code that gets the variable from the database
  $db_var = 'I like $fruit';
  extract($data);

  $return = '';
  eval('$return = "' . $db_var . '"');

  return $return;
}

// And then use this in the controller:
$details['test'] = get_variable('my_variable_name', $details);

但是当其他人可以访问数据库变量时,您真的不想使用 eval(真的不要!)。而是使用某种形式的模板,例如“我喜欢 %fruit%”,并使 get_variable 看起来像这样:

function get_variable($var, $data = array())
{
  // Here the code that gets the variable from the database
  $db_var = 'I like $fruit';
  extract($data);

  $return = $db_var;
  foreach($data as $var => $value) {
    $return = str_replace('%'.$var.'%', $value, $return);
  }

  return $return;
}

// And then use the same method in the controller:
$details['test'] = get_variable('my_variable_name', $details); // This makes all variables in details available in the database variable

【讨论】:

    猜你喜欢
    • 2011-05-15
    • 1970-01-01
    • 1970-01-01
    • 2014-06-29
    • 2012-09-30
    • 2010-10-13
    • 2015-02-06
    • 1970-01-01
    • 2015-09-04
    相关资源
    最近更新 更多