php - 如何在PHP中动态创建字符串?

标签 php string function variables eval

我有一个用于构建字符串的预定义模式,应该在整个脚本中定期创建该模式。

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

相关文章:

javascript - 确定日期是周末还是工作日

php - 试图让 PHP 和数据库协同工作

Java 相当于 ruby​​ 的 "Some sentence that I need a dynamic#{value}."

c - while(true) 之前的 printf 消失

ASM x86 FASM 中的函数参数

python - (Python)在用户定义的函数中尝试并除外

c# - 将纪元时间戳转换为日期时间

php - 解析 URL 路径的特定段的最有效方法是什么?

Javascript:确定字符串中的所有字符是否都是唯一的,如果不是,则删除重复的字符

javascript - jQuery 动画之间的延迟