Php 用数组中的变量替换字符串文本
我正在为我正在开发的游戏开发一个通知系统 我决定将消息存储为字符串,并设置“变量”以替换通过数组接收的数据 信息示例:Php 用数组中的变量替换字符串文本,php,notifications,Php,Notifications,我正在为我正在开发的游戏开发一个通知系统 我决定将消息存储为字符串,并设置“变量”以替换通过数组接收的数据 信息示例: 将显示此通知!num1,还有!num2 我从查询中收到的数组如下所示: [0] => Array ( [notification_id] => 1 [message_id] => 1 [user_id] => 3 [timestamp] => 2013-02-26 09:46:
将显示此通知!num1,还有!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和!使用数组(11,23)中的值的num2
消息在来自消息\u tbl
的查询中进行内部联接。我想棘手的部分是num3
,它存储为null
我试图将所有不同类型的消息的所有通知仅存储在两个表中
另一个例子是:
[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)?此处:
$replacers = array(11, 23);
foreach($results as &$result) {
foreach($replacers as $k => $v) {
$result['message'] = str_replace("!num" . $k , $v, $result['message']);
}
}
您可以使用正则表达式和自定义回调来执行此操作,如下所示:
$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
谢谢你这么快的回复。看起来很完美。我想我可以通过首先查找非空的值来设置
$array
?确定这是否是您需要做的。它似乎在您的演示中起作用,但当我将其放入代码中时,它返回错误:解析错误:语法错误,意外的t_函数
知道原因吗?--NVM-我的php版本设置为5.2,无法识别。更改为5.4修复了它。