2013-02-26 39 views
0

我正在爲我正在處理的遊戲設計通知系統。用數組中的變量替換字符串文本

我決定將消息存儲爲一個字符串,'變量'設置爲由通過數組接收的數據替換。消息

例子:

This notification will display !num1 and also !num2

我從我的查詢收到看起來像數組:

[0] => Array 
    (
     [notification_id] => 1 
     [message_id] => 1 
     [user_id] => 3 
     [timestamp] => 2013-02-26 09:46:20 
     [active] => 1 
     [num1] => 11 
     [num2] => 23 
     [num3] => 
     [message] => This notification will display !num1 and also !num2 
    ) 

我想要做的就是更換NUM1與NUM2用!來自陣列的值(11,23)。

消息是INNER JOIN在來自message_tbl的查詢中。我猜想棘手的部分是num3,它存儲爲空。

我試圖在所有不同類型的消息中存儲所有通知,只有2個表。

另一個例子是:

[0] => Array 
    (
     [notification_id] => 1 
     [message_id] => 1 
     [user_id] => 3 
     [timestamp] => 2013-02-26 09:46:20 
     [active] => 1 
     [num1] => 11 
     [num2] => 23 
     [num3] => 
     [message] => This notification will display !num1 and also !num2 
    ) 
[1] => Array 
    (
     [notification_id] => 2 
     [message_id] => 2 
     [user_id] => 1 
     [timestamp] => 2013-02-26 11:36:20 
     [active] => 1 
     [num1] => 
     [num2] => 23 
     [num3] => stringhere 
     [message] => This notification will display !num1 and also !num3 
    ) 

是否有PHP的方式成功地取代NUM(X)與陣列中正確的值!?

回答

1

您可以用正則表達式和一個自定義的回調,這樣做:

$array = array('num1' => 11, 'num2' => 23, 'message' => 'This notification will display !num1 and also !num2'); 
$array['message'] = preg_replace_callback('/!\b(\w+)\b/', function($match) use($array) { 
    return $array[ $match[1] ]; 
}, $array['message']); 

您可以從this demo看到這個輸出:

This notification will display 11 and also 23 
+0

感謝您的快速響應。看起來很完美。我想我可以通過首先查找非空的值來設置'$ array'。 – 2013-02-26 15:27:31

+0

當然,如果這是你需要做的。 – nickb 2013-02-26 15:27:47

+0

它似乎在你的演示,但當我把它放到我的代碼它會返回錯誤:'解析錯誤:語法錯誤,意外的T_FUNCTION'任何想法爲什麼? - NVM - 我的php版本被設置爲5.2,並且不被識別。改爲5.4固定它。 – 2013-02-26 15:36:55

1

這裏:

$replacers = array(11, 23); 
foreach($results as &$result) { 
    foreach($replacers as $k => $v) { 
     $result['message'] = str_replace("!num" . $k , $v, $result['message']); 
    } 
}