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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?