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

PHP - function associated with str_replace only run when needed

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

$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;


script.txt 包含:

The time is {{time}}  <br>
The value of PI is {{PI}}


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

您需要添加 strpos 检查。 strpos in php 用于查找子字符串在字符串中出现的位置,但如果子字符串从未出现,则它将 return 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;

?>