2013-02-26 38 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']); 
    } 
}