dsfw2154 2012-03-24 17:08
浏览 27
已采纳

如何在[] [关闭]之间查找文本

I have a text like this

[name:roccos] [phone:123324324] [tags:abc def ghi] [id:value]

How can i find the values of name, phone, etc using php, So i should have variable like this $name = 'roccos' $phone = '123324324', I can either do this for all separately or is there any way to automatically get all variables along with value automatically...

Ex : In this text [abc:def] [phone:123456] everything before the colon : will be the variable name and after the colon will be it's value => $abc = 'def' $phone = '123456'

  • 写回答

1条回答 默认 最新

  • dqc3469 2012-03-24 17:11
    关注

    Just use a regular expression, and preg_match_all:

    $str = '[name:roccos] [phone:123324324] [tags:abc def ghi] [id:value]';
    preg_match_all('/\[(.*?):(.*?)\]/', $str, $matches, PREG_SET_ORDER);
    $data = array();
    
    foreach($matches as $match) {
        $data[$match[1]] = $match[2];
    }
    

    Here's a demo. Note that I used an array to hold the data instead of directly assigning them to global variables; that would be dangerous if you were taking this from any kind of user input. If the data is safe, you can expand it using extract:

    extract($data);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看