开发者

Effective, and Non-Redundant PHP code

I have the following PHP excerpt code:

foreach($afb_replacements as $afb_to_replace => $afb_replacement) {
    $sender_subject     = str_replace($afb_to_replace, $afb_replacement, $sender_subject);
    $ar_subject         = str_replace($afb_to_replace, $afb_replacement, $ar_subject);

    $final_message      = str_replace($afb_to_replace, $afb_replacement, $final开发者_如何学运维_message);
    $final_message_text = str_replace($afb_to_replace, $afb_replacement, $final_message_text);

    $ar_message         = str_replace($afb_to_replace, $afb_replacement, $ar_message);
    $ar_message_text    = str_replace($afb_to_replace, $afb_replacement, $ar_message_text);
}

All 6 variables are replaced in the same manner (same text to replace with the same replacement in all variables with $afb_to_replace and $afb_replacement).

What I want to know is:

How can this be written more effectively? Perhaps in one line of code. I am sure there is a better way, since this is redundant code but no other solution comes into my mind at the moment. Any ideas?

I am curios about your approach!


This should do exactly the same thing:

$in = array($sender_subject, $ar_subject, $final_message, $final_message_text, $ar_message, $ar_message_text);
$out = str_replace(array_keys($afb_replacements), array_values($afb_replacements), $in);
list($sender_subject, $ar_subject, $final_message, $final_message_text, $ar_message, $ar_message_text) = $out;

I split it onto three lines for readability.

str_replace() accepts arrays for search, replace and subject.

edit: here's an even prettier solution suggested by BoltClock

$in = compact('sender_subject', 'ar_subject', 'final_message', 'final_message_text', 'ar_message', 'ar_message_text');
$out = str_replace(array_keys($afb_replacements), array_values($afb_replacements), $in);
extract($out);


str_replace accepts arrays for the subject argument (and the needle and haystack if you like). So you could do this:

$vars = str_replace($afb_to_replace, $afb_replacement, $vars);

http://php.net/manual/en/function.str-replace.php


$bad = array('a', 'b', 'c');
$good = array('x', 'y', 'z');
$old = array($sender_subject, $ar_subject, $final_message, $final_message_text, ...);
$new = str_replace($bad, $good, $old);

Or if you don't want to change your current $afb_replacements array, it could be done this way (stealing code from @James C):

$bad = array_keys($afb_replacements);
$good = array_values($afb_replacements);
$old = array($sender_subject, $ar_subject, $final_message, $final_message_text, ...);
$new = str_replace($bad, $good, $old);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜