我正在制作一款游戏的通知系统。
我决定将消息存储为带有'变量'的字符串,设置为通过数组接收的数据替换。
消息示例:
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
)
我想做的是用数组(11,23)中的值替换!num1和!num2。
消息在message_tbl
的查询中被INNER join。我想棘手的部分是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)替换为数组中的正确值?
您可以使用正则表达式和自定义回调来完成此操作,如下所示:
$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
此处:
$replacers = array(11, 23);
foreach($results as &$result) {
foreach($replacers as $k => $v) {
$result['message'] = str_replace("!num" . $k , $v, $result['message']);
}
}