1

像这样的东西:

$vars = array("key" => "value", "key2" => "value2" //..etc);

function ($template, $vars) {
  $file = file_get_contents($template);
  foreach ($vars as $key => $value) {
    str_replace($template //this is where I get confused);

  }
}

这个想法是获取模板文件的内容(仅包括 html),然后 foreach 将运行并将作为 vars 数组内“键”的文本替换为 vars 数组内的“值”字段的文本。因此,假设我的模板文件文本中有某个地方,例如“{content}”。该函数应该找到该字符串(包括我知道我没有在示例中指定它们的大括号)并将其替换为数组中的相应值。

我觉得我对 str_replace() 函数的理解不够。PHP.net 也没有多大帮助,据我了解,它是这样的:

str_replace($replacethese, $withthese, $inthisfile);

很简单,但是当我的数组是二维的时,我该怎么做呢?我的“$replacethese”参数必须是 $vars 数组的“键”值。

4

3 回答 3

2

您可以使用array_keys()andarray_values()来获取$vars. 试试这个:

$replace = array_keys($vars);
$with = array_values($vars);
$file = str_replace($replace, $with, $file);

编辑:

@EL 说那strtr()更好:)。所以你可以试试:

$file = strtr($file, $vars);
于 2013-03-09T17:36:22.383 回答
1

您不需要 foreach 循环,只需像这样的单个 str_replace 调用就可以完成这项工作:

str_replace(array_keys($vars), array_values($vars), $fileData);
于 2013-03-09T17:37:12.790 回答
0
<?php
function ($template, $vars) {
  $data = file_get_contents($template);
  $data = str_replace(array_keys($vars), array_values($vars), $data);
  file_put_contents($template, $data);
}
于 2013-03-09T17:37:15.373 回答