有效且非冗余的 PHP 代码


Effective, and Non-Redundant PHP code

我有以下PHP摘录代码:

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

所有 6 个变量都以相同的方式替换(在所有变量中用 $afb_to_replace 和 $afb_replace 替换相同的文本替换相同的文本)。

我想知道的是:

如何才能更有效地编写?也许在一行代码中。我相信有更好的方法,因为这是多余的代码,但目前我没有想到其他解决方案。有什么想法吗?

我对你的方法感到好奇!

这应该做完全相同的事情:

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

为了便于阅读,我将其分成三行。

str_replace()接受用于搜索、替换和主题的数组。

编辑:这是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接受主题参数的数组(如果你愿意,还可以接受针和大海捞针)。所以你可以这样做:

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

或者,如果您不想更改当前的$afb_replacements数组,可以通过以下方式完成(从 @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);