用数组中的变量替换字符串文本

时间:2013-02-26 15:19:40

标签: php notifications

我正在为我正在进行的游戏制作通知系统。

我决定将消息存储为字符串,并将“变量”设置为由通过数组接收的数据替换。

消息示例:

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的查询中的

消息是INNER JOINed。我认为棘手的部分是num3,它存储为null。

我试图仅在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)?

2 个答案:

答案 0 :(得分:1)

这里:

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

答案 1 :(得分: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