Sunday, January 2, 2022

[FIXED] Can't replace variable names in string

Issue

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?


Solution

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.



Answered By - Ben Hillier

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.