2011-05-15 57 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);