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 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分