【问题标题】:How to replace text in a file with str_replace?如何用str_replace替换文件中的文本?
【发布时间】:2013-03-09 17:30:52
【问题描述】:

类似这样的:

$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 数组的“键”值。

【问题讨论】:

    标签: php arrays foreach str-replace


    【解决方案1】:

    您可以使用array_keys()array_values() 来获取$vars 的键和值。试试这个:

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

    编辑:

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

    $file = strtr($file, $vars);
    

    【讨论】:

      【解决方案2】:

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

      str_replace(array_keys($vars), array_values($vars), $fileData);
      

      【讨论】:

        【解决方案3】:
        <?php
        function ($template, $vars) {
          $data = file_get_contents($template);
          $data = str_replace(array_keys($vars), array_values($vars), $data);
          file_put_contents($template, $data);
        }
        

        【讨论】:

          猜你喜欢
          • 2011-07-28
          • 2012-01-03
          • 2014-02-07
          • 2020-12-26
          • 2011-10-03
          • 1970-01-01
          • 2020-01-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多