PHP - 与str_replace关联的函数仅在需要时运行

时间:2017-03-15 17:19:39

标签: php templates replace str-replace

我使用str_replace()函数替换文本文件中的某些内容。我的代码:

@for (int i = 0; i < Model.Images.Count(); i++)
{
<div class="form-group">
   @Html.LabelFor(x=> x.Images[i].Image_URL, htmlAttributes: new { @class = "control-label col-md-2" })
   <div class="col-md-10">
      @Html.EditorFor(x=> x.Images[i].Image_URL, new { htmlAttributes = new { @class = "form-control" } })
      @Html.ValidationMessageFor(x => x.Image[i].Image_URL, "", new { @class = "text-danger" })
   </div>
</div>
}


script.txt包含:

$txt = file_get_contents('script.txt');
function makefile() {
   $file = fopen("test.txt","w");
   fwrite($file,"Hello World. Testing!");
   fclose($file);
   return "Done!";
}
$templates = array("{{time}}", "{{PI}}", "{{make}}");
$applied = array(date("h:i:sa"), 22/7, makefile());
$str = str_replace($templates, $applied , $txt);
echo $str;


如您所见,它只是一个简单的模板系统。 makefile()函数仅用于测试目的。 script.txt文件没有{{make}}个模板。通常,在替换操作期间不需要调用makefile函数。但是当我运行代码时,它会创建test.txt。这意味着makefile()运行。有没有办法避免这种不必要的功能操作?并在需要时运行它们?

1 个答案:

答案 0 :(得分:1)

您需要添加strpos支票。 php中的strpos用于查找字符串中出现子字符串的位置,但如果子字符串永远不会发生,则返回false。利用这一点,我们可以做到:

<?php

$txt = "The time is {{time}}  <br>
The value of PI is {{PI}}";
function makefile() {
   $file = fopen("test.txt","w");
   fwrite($file,"Hello World. Testing!");
   fclose($file);
   return "Done!";
}
$templates = array("{{time}}", "{{PI}}", "{{make}}");
$applied = array(date("h:i:sa"), 22/7, strpos($txt,"{{make}}") ? makefile() : false);
$str = str_replace($templates, $applied , $txt);
echo $str;

?>