duanlu0075 2013-02-26 15:19
浏览 65
已采纳

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

I am working on a notification system for a game i'm working on.

I decided to store messages as a string with 'variables' set up to be replaced by the data received through an array.

Example of the message:

This notification will display !num1 and also !num2

The array I receive from my query will look like:

[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
    )

What I want to do is replace !num1 and !num2 with the values from the array (11, 23).

message is INNER JOINed in a query from the message_tbl. I suppose the tricky part is num3 which is stored as null.

I am trying to store all notifications for all different types of messages in only 2 tables.

Another example would be :

[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
    )

Is there a way in PHP to successfully replace the !num(x) with the correct value in the array?

  • 写回答

2条回答 默认 最新

  • dowy77780 2013-02-26 15:23
    关注

    You can do this with a regular expression and a custom callback, like this:

    $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']);
    

    You can see from this demo that this outputs:

    This notification will display 11 and also 23 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题