PHP 中的嵌套(多个)字符串插值

Nested (multiple) string interpolation in PHP

如果我有一个包含嵌套变量的变量,例如:

$message = "Hello $user_name, an email was send to $user_email ...";
$user_name = 'User Name';
$user_email = 'user@email.com';

是否可以产生如下输出:

Hello User Name, an email was send to user@email.com ...

不调用 eval()?

是的,可以将变量 $user_email$user_name 放在 $message 上方,以便它们首先实例化。

$user_email = 'user@email.com';
$user_name = 'User Name';
$message = "Hello $user_name, an email was send to $user_email ...";

echo $message; //Will output: Hello User Name, an email was send to user@email.com ...

编辑:阅读您的反应后,您可以使用闭包,例如:

$message = function($name = null, $email = null){
  return "Hello $name, an email was send to $email ...";
};

$user_name = 'User Name';
$user_email = 'user@email.com';

$newMessage = $message($user_name, $user_email);

您可以 'define' 占位符并在需要的地方替换它。

$message = "Hello #user_name#, an email was send to #user_email# ...";
$user_name = 'User Name';
$user_email = 'user@email.com';

$newMessage = str_replace(array("#user_name#", "#user_email#"), array($user_name, $user_email), $message);

参考str_replace

使用sprintf or printf函数:

$message = "Hello %s, an email was send to %s ...";
$user_name = 'User Name';
$user_email = 'user@email.com';

echo sprintf($message, $user_name, $user_email);

printf($message, $user_name, $user_email);
$user_email = 'user@email.com';
$user_name = 'User Name';
$message = "Hello " . $user_name . ", an email was send to " . $user_email . " ...";