首页 > 解决方案 > 无法替换字符串中的变量名

问题描述

我想发送一条系统消息,用他的名字称呼用户。消息存储在 .txt 文件中,如下所示:

你好 $user-> 名字

登录链接: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); 

但是,我在此之后的输出仍然与文本文件中的完全相同。我究竟做错了什么?

标签: phpyii

解决方案


我认为这可能就像在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


推荐阅读