yii 无法替换字符串[duplicate]中的变量名

wmvff8tz  于 2022-11-09  发布在  其他
关注(0)|答案(2)|浏览(91)

此问题在此处已有答案

What is the difference between single-quoted and double-quoted strings in PHP?(7个答案)
两年前就关门了。
我想发送一条系统消息,以用户的名字作为地址。该消息存储在一个.txt文件中,格式为:
你好$user-〉名字
登录链接:something.something/用户名/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);

但是,我在这之后的输出仍然和文本文件中的完全一样。我做错了什么?

insrf1ej

insrf1ej1#

我想这可能就像在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需详细信息,请参阅www.example.com。

6qftjkof

6qftjkof2#

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

双引号内的变量将被替换--因此,您不是在尝试替换 text$user->firstname,而是在尝试替换文本George(假设这是用户的名字)--但是,在您的输入文本中没有George,因此......没有要替换的内容。
请使用单引号,或使用\转义$符号

相关问题