我正在创建一个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;
}
我想知道这是最好的方法还是有更好的方法?
答案 0 :(得分:10)
如果没有必要,切勿使用该死的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。
答案 1 :(得分:2)
你需要的是printf函数。 你可以定义一个字符串,并将%s作为字符串的占位符。
然后致电
printf($variable, $string1, $string2, $string);
第一个%s被$ string1替换,依此类推。
在你的例子中,我会使用vsprintf返回字符串,你可以给出一个数组,这样你可以提供你喜欢的每个params数组和输入字符串
继承你的榜样:
<?
$msg = '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];
$newmsg = vsprintf($msg,array($user,$color));
echo $newmsg."\n";
}
?>
答案 2 :(得分:0)
我更喜欢这种方式:
<?php
$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];
$newmsg = str_replace(array('[USER]', '[COLOR]'), array($user, $color), $msg);
echo $newmsg;
}
?>
答案 3 :(得分:0)
$colors = array("red","green","blue","yellow");
$users = array("bob","craig","ted","dirty sanchez");
$messages = array_combine($colors, $users);
foreach ($messages as $color => $user)
{
echo "Hello $user, your favourite color is $color";
}
使用array_combine以$ keys =&gt;格式创建数组; $ values生成以下数组:
"red" => "bob",
"green" => "craig",
"blue" => "ted",
"yellow" => "dirty sanches"
答案 4 :(得分:0)
您可以使用strtr功能
$msg = 'Hello @user, your favorite color is @color';
echo strtr($msg, array('@user'=>'bob', '@color'=>'red'));
输出:
Hello bob, your favorite color is red