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

报告相同问题?

悬赏问题

  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!