2011-05-15 58 views
2

我有以下的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)。

我想知道的是:

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

我对你的方法很好奇!

回答

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); 
+0

如果你使用'compact()'和'extract()',它会保存一些变量名的输入。 – BoltClock 2011-05-15 19:47:47

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