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) 中的值。

消息在来自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) ?

4

2 回答 2

1

这里:

$replacers = array(11, 23);
foreach($results as &$result) {
    foreach($replacers as $k => $v) {
        $result['message'] = str_replace("!num" . $k , $v, $result['message']);
    }
}
于 2013-02-26T15:22:43.330 回答
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 notification will display 11 and also 23 
于 2013-02-26T15:23:18.120 回答