PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, January 2, 2022

[FIXED] Can't replace variable names in string

 January 02, 2022     php, yii     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing