douwen8118 2013-08-01 08:32
浏览 29
已采纳

使用数据库中的值替换字符串中的自定义标记

what I need to do is to parse a string similar to this:

{a}3{/a}*{b}4{/b}

or this

{a}3{/a}/{b}2{/b}*100

I need to substitute in that string those values within the tags with real values from the database, the first example:

SELECT value FROM table WHERE id = 3;

SELECT value FROM table WHERE id = 4;

This function:

preg_replace_callback('/(?>{([^}]+)})(.*)?{\/\1}/sim', 'find_tags_callback', $string);

Actually returns the ids contained in the string, the problem is that I'm stuck there. In pseudo code I would need to:

Extract the first id from the string.

Run my query.

Substitute that id with the correct value.

[Do the same for all tags]

Finish having back the initial string with the correct value inside. The first might be

10*3

the second

40/90*100

Any idea how to do this, I'm completely stuck.

Thanks

  • 写回答

1条回答 默认 最新

  • douhe4336 2013-08-01 09:12
    关注

    Do a database query to get all the values, and put them into an array keyed off the IDs. In the code below, I assume the array is named $tags.

    $new_string = preg_replace_callback('/\{([^}]+)\}(.+?)\{/\1\}/sim', 
        function ($match) use ($tags) {
            return $tags[$match[2]];
        }, $string);
    

    The use ($tags) declaration allows the function to reference the external variable $tags.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

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