开发者

php eval function and performance

Im creating a web app where I want all of the responses to the user stored in a language file for easy editing. So Im using eval() to manage dynamic messages lik so:

$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开发者_如何学JAVA $newmsg;


}

Im wondering if this is the best approach or if there is a better way?


Never use that damn eval if not necessary! Your code won't work, you should use sprintf for your purpose.

$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);
}

Assuming you're using this for comments or other user-supplied text, I've added htmlentities() to prevent XSS.


what you need is the printf function. you can define a string and have %s as place holder for a string.

then call

printf($variable, $string1, $string2, $string);

the first %s gets replaced by $string1 and so on.

in your very example i would use vsprintf which returns the string and you can give an array so you can feed it what every array of params and input string you like

heres your example:

   <?
$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";
}

?>


I prefer this way:

<?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;
}
?>


$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";
}

Using array_combine which creates arrays in the format $keys => $values making the following array:

"red" => "bob",
"green" => "craig",
"blue" => "ted",
"yellow" => "dirty sanches"


You can use the strtr function

$msg = 'Hello @user, your favorite color is @color';
echo strtr($msg, array('@user'=>'bob', '@color'=>'red'));

Output:

Hello bob, your favorite color is red
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜