有效且非冗余的PHP代码

时间:2011-05-15 19:32:21

标签: php

我有以下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_replacement替换所有变量中的相同替换)。

我想知道的是:

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

我很好奇你的方法!

3 个答案:

答案 0 :(得分:5)

这应该做同样的事情:

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

答案 1 :(得分:0)

str_replace接受主题参数的数组(如果你愿意,可以接受针和干草堆)。所以你可以这样做:

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

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

答案 2 :(得分:0)

$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);
相关问题