我有一个用于构建字符串的预定义模式,应该在整个脚本中定期创建该模式。
$str="$first - $second @@ $third"; // pattern for building the string
$first="word1";
$second="word2";
$third="word3";
$string= ..?? // string should be built here based on the pattern
目前,我正在使用 eval
根据最初定义的模式生成字符串。但是,由于这种情况偶尔会发生,而且 eval
通常都很糟糕,所以我希望找到另一种方法。
注意,该模式在所有代码之上仅定义一次,并且我只能通过一行编辑所有脚本的模式。因此,$string
的组成部分不应受到任何更改。
我尝试了create_function
,但需要相同数量的参数。使用eval
,我可以轻松更改模式,但使用create-function
,我需要更改整个脚本。例如,如果将字符串模式更改为
$str="$first @@ $second"; // One arg/var is dropped
评估示例:
$str="$first - $second @@ $third"; // Pattern is defined one-time before codes
$first="word1";
$second="word2";
$third="word3";
eval("\$string = \"$str\";");
create_function 示例:
$str=create_function('$first,$second,$third', 'return "$first - $second @@ $third";');
$string=$str($first,$second,$third);
最佳答案
您可以使用 sprintf
提供的字符串格式化功能或vsprintf
.
$format = "%s - %s @@ %s"; // pattern for building the string
$first = "word1";
$second = "word2";
$third = "word3";
$string = sprintf($format, $first, $second, $third);
如果您想传递数组,可以使用vsprintf
。
$format = "%s - %s @@ %s"; // pattern for building the string
$values = array($first, $second, $third);
$string = vsprintf($format, $values);
关于php - 如何在PHP中动态创建字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13244948/