php如何在不打印的情况下解析变量替换

php如何在不打印的情况下解析变量替换,php,string,laravel,variables,substitution,Php,String,Laravel,Variables,Substitution,如何解析字符串中的变量 下面是一个示例代码: $str = "12345"; $str2 = "STR:{$str}"; $str3 = $str2; echo $str2; echo $str3; 但这些都不起作用: $otp = 12345; $template = MessageTemplate::where('type',1)->first(); //db query $message = $template->content; //content field, "OTP

如何解析字符串中的变量

下面是一个示例代码:

$str =  "12345";
$str2 = "STR:{$str}";
$str3 = $str2;
echo $str2;
echo $str3;
但这些都不起作用:

$otp = 12345;
$template = MessageTemplate::where('type',1)->first(); //db query
$message = $template->content; //content field, "OTP:{$otp}" 
echo $message;
此代码打印
OTP:{$OTP}
而不是
OTP:12345

这就是我们需要的:

$member=member::where('id',$id)->with('position')->with('company')->first();
$otp=12345;
$template=MessageTemplate::where('type',1)->first()//数据库查询
$message=$template->content//内容字段,“OTP:{$OTP}”
$sms=sms::创建(['mobile'=>$member->mobile,'message'=>$message]);

此代码打印
OTP:{$OTP}
而不是
OTP:12345

谢谢你的回复。实际上,我需要的是在将其保存到数据库之前对其进行解析。字符串“OTP:12345”应写回数据库。而且,变量是动态的。它是一个允许管理员自定义消息的模板,因此管理员可以根据需要添加任意多的变量。例如: “{$member->title},{$member->firstName},{$member->lastName},以验证您是{$member->company->name}的{$mamber->position->name}。输入代码{$otp}”


所以我不能用str_替换。而且我们的数据库还支持json,因此管理员可以向$member添加一个自定义属性

// MessageTemplate class
public function getContentAttribute($string)
{
    return 'OTP:' . $string;
}

// anywhere in controller
$message = $template->content; // will call content mutator
echo $message;

您可以像这样在模型中使用变体

// MessageTemplate class
public function getContentAttribute($string)
{
    return 'OTP:' . $string;
}

// anywhere in controller
$message = $template->content; // will call content mutator
echo $message;

$template->content的值只是一个字符串

您只需执行替换操作:

$message = str_replace('{$otp}', $otp, $template->content);

$template->content的值只是一个字符串

您只需执行替换操作:

$message = str_replace('{$otp}', $otp, $template->content);

$otp=“12345”;尝试使用字符串。
str\u replace/preg\u replace
仅限。这是否回答了您的问题$otp=“12345”;尝试使用字符串。
str\u replace/preg\u replace
仅限。这是否回答了您的问题?