The task is to create a variable (string) in which there will be variables that will be replaced with a value during the output.

Like that:

$s1 = "it's $s2 !"; $s2 = 'OK'; echo $s1; //не работает echo "it's $s2 !"; //должно работать так 

Maybe I'm not right approach to solving the problem. Line $ s1 is a piece of HTML code that is output in a loop and the variable $ s2 is constantly changing. Actually, I know how to solve using a function, but the variant with variables seemed more elegant to me.

  • The $s2 variable must exist when you create $s1 , since it is used in the contents. - Visman
  • I understand why the error, I do not understand how to fix it) - wakh.ru
  • Can you escape the $ sign when creating the first variable? Or also not? - Visman
  • This seems to be just what you need, but I tried - it does not work, can you give an example of code? - wakh.ru

3 answers 3

Since you do not change variables in some places, use the strtr () function

 $s1 = "it's \$s2 !"; $s2 = 'OK'; echo strtr($s1, ['$s2' => $s2]); 

Http://sandbox.onlinephpfunctions.com/code/cbc725c89ce1a85ccfc58dd401350b34568ca39d test

  • Thank you, thought about this. Apparently this is the best solution. - wakh.ru

Use variable shielding in a string, followed by searching and replacing with one of the appropriate functions for this purpose. For example, str_replace () :

 $s1 = "it's \$s2 !"; $s2 = 'OK'; echo str_replace('$s2', $s2, $s1); // it's OK ! 
  • Brilliant!)) Variables are created in different places and of course the order of creation cannot be changed, otherwise the meaning will just disappear. - wakh.ru
  • supplemented the question. - wakh.ru
  • @ wakh.ru in order to receive your messages in a timely manner, in front of the username to which you are sending a comment, register the dog @ . - Edward
  • @ wakh.ru edited your answer according to your editing in the PP. - Edward
  • Thank you, you are a bit ahead with a similar decision. - wakh.ru

you have $s2 not yet initialized

 $s2 = 'OK'; $s1 = "it's $s2 !"; echo $s1; echo "it's $s2 !"; 
  • This is already written above. - wakh.ru