如何解析字符串中的变量?
这里是有效的示例代码:
$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
感谢您的回复。实际上,我需要在将其保存到数据库之前对其进行解析。字符串“ OTP:12345”应写回到数据库。而且,变量是动态的。它是允许管理员自定义消息的模板,因此管理员可以根据需要添加任意多个变量。例如:“ {$ member-> title},{$ member-> firstName},{$ member-> lastName},以验证您是{$ member-的{$ mamber-> position-> name} > company-> name}。输入代码{$ otp}”。所以我不能使用str_replace。而且我们的数据库支持json,因此管理员可以向$ member
添加自定义属性您可以像这样在模型中使用增变器
// MessageTemplate class
public function getContentAttribute($string)
{
return 'OTP:' . $string;
}
// anywhere in controller
$message = $template->content; // will call content mutator
echo $message;