How to manually interpolate a string?

The only way I found string interpolation (IE to expand variables inside it) is this:

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

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

Is there a better way to expand a single quote string without using eval ()? I am looking for something that PHP itself provides.

Pay attention . Using strtr () is similar to using sprintf (). My question is different from the question related to a possible duplicate section of this question, since I allow the line to control how (IE through which calls to functions or property accessories) it wants to receive content.

+6
source share
3 answers

Here's a possible solution, not sure about your specific scenario, if that works for you, but it would certainly eliminate the need for so many single and double quotes.

 <?php class a { function b() { return "World"; } } $c = new a; echo eval('Hello {$c->b()}.'); ?> 
0
source

There are more mechanisms than the PHP string literal syntax for replacing placeholders in strings! Pretty common sprintf :

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

http://php.net/sprintf

There are tons of other more or less specialized template languages. Choose the one you like best.

+4
source

Have you heard of strtr() ? http://php.net/manual/en/function.strtr.php

it fulfills this very goal and is very useful for creating dynamic html information containing information from a database for example

The following line is given:

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

then you can strtr() it with strtr() :

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

While sprintf is faster on, strtr allows you to control what is going on in a more friendly way ( sprintf actually can't handle very long lines containing a hundred replaceable placeholders)

0
source

Source: https://habr.com/ru/post/972704/


All Articles