Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I manually interpolate a string? [duplicate]

The only way I've found to interpolate a string (that is, expand the variables inside it) is the following:

$str = 'This is a $a';
$a = 'test';
echo eval('return "' . $str . '";');

Keep in mind that in a real-life scenario, the strings are created in different places, so I can't just replace 's with "s.

Is there a better way for expanding a single-quoted string without the use of eval()? I'm looking for something that PHP itself provides.

Please note: Using strtr() is just like using something like sprintf(). My question is different than the question linked to in the possible duplicate section of this question, since I am letting the string control how (that is, through what function calls or property accessors) it wants to obtain the content.

like image 401
Parham Doustdar Avatar asked Jul 23 '14 13:07

Parham Doustdar


2 Answers

There are more mechanisms than PHP string literal syntax to replace placeholders in strings! A pretty common one is sprintf:

$str = 'This is a %s';
$a   = 'test';
echo sprintf($str, $a);

http://php.net/sprintf

There are a ton of other more or less specialised templating languages. Pick the one you like best.

like image 55
deceze Avatar answered Sep 28 '22 05:09

deceze


Have you heard of strtr()?

It serves this very purpose and is very useful to create dynamic HTML content containing information from a database, for example.

Given the following string:

$str = 'here is some text to greet user {zUserName}';

then you can parse it using strtr():

$userName = 'Mike';
$parsed = strtr($str,array('{zUserName}'=>$userName));
echo $parsed; // outputs: 'here is some text to greet user Mike'

While sprintf is faster in some regards, strtr allows you to control what goes where in a more friendly way (sprintf is not really manageable on very long strings containing, say, a hundred placeholders to be replaced).

like image 21
Félix Adriyel Gagnon-Grenier Avatar answered Sep 28 '22 05:09

Félix Adriyel Gagnon-Grenier