douchui1488 2011-06-27 07:59
浏览 20
已采纳

自定义标记与Php

I'm working on a social networking site. When sending a notification, you for example could type [user:20:name] in the notification as a developer in the text you send. So say i send

"[user:20:name] commented on your [video:8:name,link] video"

it would show up as "Bob commented on your iOS 5 review video".

So it would see user, see the user id and that i wanted the name, it would then do the work in the database it needs and replace [user:20:name] in the string with Bob.

For the video it would know i wanted the name for video 8 as a link. How would i parse something like this? I already know how to grab data from the database. Just stuck on this part. Any idea how?

One of the idea was to get each [markup] by its self, and do the parsing on each one, then str_replace it when i get the processed version of the markup.

Not sure how i would get each [markup] by it self.

  • 写回答

2条回答 默认 最新

  • douxiao0400 2011-06-27 08:56
    关注

    Not sure if this is too simple, it doesn't deal with multiple tags in a string but you could try something like this as a starting point:

    <?php
    
    // the original string
    $str = 'User [user:20:name] did foo bar.';
    
    // find the tag
    preg_match('/(?<=\[)[a-z0-9:]+(?=\])/', $str, $tags);    
    
    // build a db query
    list($table, $id, $field) = explode(':', $tags[0]);
    $sql = sprintf('SELECT %s FROM %s WHERE id = %d', $field, $table, $id);
    
    // DB query... returns user 'Bob'
    $user = 'Bob';
    
    // replace the original tag with the user's name
    $output = preg_replace('/\[user:\d+:name\]/', $user, $str);  
    

    Update

    For multiple tags you could use preg_match_all() and then iterate over the $tags array, probably using the $table variable as a key to build an array of query data... you'd have to decide on the most efficient way to use this data to query your database, based on your database implementation. if you can use PDO prepared statements might be good. so would caching your output because you don't want to preg match and replace all your output every time... or just perform this operation one time and store the output in the database.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 关于多单片机模块化的一些问题
  • ¥30 seata使用出现报错,其他服务找不到seata
  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取
  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection