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

时间:2015-05-06 11:05:05

标签: php string string-interpolation

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

$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()

4 个答案:

答案 0 :(得分:2)

是的,可以将变量$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);

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

file.seek(0)

答案 1 :(得分:1)

您可以'定义'占位符并将其替换为您需要的位置。

$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以供参考。

答案 2 :(得分:1)

使用sprintfprintf功能:

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

答案 3 :(得分:0)

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