我正在创建一个Web应用程序,我希望将所有对用户的响应存储在语言文件中以便于编辑.所以我使用eval()管理动态消息,这样:
$msg = 'Hello $user, your favorite color is $color'; $colors = array("red","green","blue","yellow"); $users = array("bob","craig","ted","dirty sanchez"); foreach($users as $key => $user){ $color = $colors[$key]; eval("\$newmsg = \"$msg\";"); echo $newmsg; }
我想知道这是最好的方法还是有更好的方法?
如果没有必要,切勿使用该死的eval!你的代码不起作用,你应该使用sprintf.
$messageFormat = 'Hello %s, your favorite color is %s'; $colors = array("red","green","blue","yellow"); $users = array("bob","craig","ted","dirty sanchez"); foreach($users as $key => $user){ $color = $colors[$key]; $actualMessage = sprintf($messageFormat, $user, $color); echo htmlentities($actualMessage); }
假设您将此用于评论或其他用户提供的文本,我已添加htmlentities()
以防止XSS.