0

I want to send a system message that addresses the user with his first name. The message is stored in a .txt file as:

Hello $user->firstname

Login link: something.something/user/id

In the userController (where the message is sent from) I'm now trying to replace the $user->firstname with the actual $user->firstname:

$output = file_get_contents(Yii::$app->basePath."message.txt");
$user = $this->findModel($id); //this is tested and works

$output = str_replace("$user->firstname", $user->firstname, $output); 

However, my output after this is still the exact same as in the text file. What am I doing wrong?

  • If you are unsure what is happening at times, worth trying to display some of the values for debugging purposes, something like `echo "$user->firstname";` will show what is happening. – Nigel Ren Jun 03 '20 at 14:04

2 Answers2

2

I think it might be as simple as using single quotes in your str_replace call:

$output = str_replace('$user->firstname', $user->firstname, $output);

When you use double quotes, PHP has already tried to replace the string before calling str_replace.

See https://www.php.net/manual/en/language.types.string.php#language.types.string.parsing for more information.

Ben Hillier
  • 2,126
  • 1
  • 10
  • 15
0
$output = str_replace("$user->firstname", $user->firstname, $output); 

Variables inside double quotes get replaced - so you are not trying to replace the text $user->firstname here, you are trying to replace the text George (assuming that was the users first name) - but there is no George in your input text, so … nothing to replace.

Use single quotes, or escape the $ sign with a \

CBroe
  • 91,630
  • 14
  • 92
  • 150