Nikola Obreshkov
Nikola Obreshkov

Reputation: 1748

Nested (multiple) string interpolation in PHP

If I have a variable that contains nested variables, e.g.:

$message = "Hello $user_name, an email was send to $user_email ...";
$user_name = 'User Name';
$user_email = '[email protected]';

is it possible to produce an output such as:

Hello User Name, an email was send to [email protected] ...

without calling eval()?

Upvotes: 1

Views: 1025

Answers (4)

Gurpreet Khattra
Gurpreet Khattra

Reputation: 111

$user_email = '[email protected]';
$user_name = 'User Name';
$message = "Hello " . $user_name . ", an email was send to " . $user_email . " ...";

Upvotes: 0

Toto
Toto

Reputation: 91488

Using sprintf or printf function:

$message = "Hello %s, an email was send to %s ...";
$user_name = 'User Name';
$user_email = '[email protected]';

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

or

printf($message, $user_name, $user_email);

Upvotes: 2

Daan
Daan

Reputation: 12246

Yes it's possible just place the variables $user_email and $user_name above $message so they become instantiated first.

$user_email = '[email protected]';
$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 [email protected] ...

EDIT: After reading your reaction you could use a closure for example:

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

$user_name = 'User Name';
$user_email = '[email protected]';

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

Upvotes: 3

take
take

Reputation: 2222

You can 'define' placeholders and replace it where you need it.

$message = "Hello #user_name#, an email was send to #user_email# ...";
$user_name = 'User Name';
$user_email = '[email protected]';

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

See str_replace for reference.

Upvotes: 3

Related Questions