无法替换字符串中的变量名
Can't replace variable names in string
我想发送一条系统消息,用他的名字称呼用户。该消息存储在 .txt 文件中,如下所示:
Hello $user->firstname
Login link: something.something/user/id
在 userController(发送消息的地方)中,我现在尝试用实际的 $user->firstname 替换 $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);
但是,此后我的输出仍然与文本文件中的输出完全相同。我做错了什么?
我认为这可能就像在您的 str_replace
调用中使用单引号一样简单:
$output = str_replace('$user->firstname', $user->firstname, $output);
当您使用双引号时,PHP 在调用 str_replace
之前已经尝试替换字符串。
有关详细信息,请参阅 https://www.php.net/manual/en/language.types.string.php#language.types.string.parsing。
$output = str_replace("$user->firstname", $user->firstname, $output);
双引号内的变量被替换 - 所以你不是要替换 text $user->firstname
这里,你是要替换文本 George
(假设那是用户的名字)- 但是您的输入文本中没有 George
,所以……没有什么可替换的。
使用单引号,或使用 \
转义 $ 符号
我想发送一条系统消息,用他的名字称呼用户。该消息存储在 .txt 文件中,如下所示:
Hello $user->firstname
Login link: something.something/user/id
在 userController(发送消息的地方)中,我现在尝试用实际的 $user->firstname 替换 $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);
但是,此后我的输出仍然与文本文件中的输出完全相同。我做错了什么?
我认为这可能就像在您的 str_replace
调用中使用单引号一样简单:
$output = str_replace('$user->firstname', $user->firstname, $output);
当您使用双引号时,PHP 在调用 str_replace
之前已经尝试替换字符串。
有关详细信息,请参阅 https://www.php.net/manual/en/language.types.string.php#language.types.string.parsing。
$output = str_replace("$user->firstname", $user->firstname, $output);
双引号内的变量被替换 - 所以你不是要替换 text $user->firstname
这里,你是要替换文本 George
(假设那是用户的名字)- 但是您的输入文本中没有 George
,所以……没有什么可替换的。
使用单引号,或使用 \
转义 $ 符号