dongpi3237 2014-01-18 20:51
浏览 24

如何将搜索网址拆分为关联数组

So I would like to take a string like this,

q=Sugar Beet&qf=vegetables&range=time:[34-40]

and break it up into separate pieces that can be put into an associative array and sent to a Solr Server.

I want it to look like this

['q'] => ['Sugar Beets], ['qf'] => ['vegetables']

After using urlencode I get

q%3DSugar+Beet%26qf%3Dvegetables%26range%3Dtime%3A%5B34-40%5D

Now I was thinking I would make two separate arrays that would use preg_split() and take the information between the & and the = sign or the = and the & sign, but this leaves the problem of the final and first because they do not start with an & or end in an &.

After this, the plan was to take the two array and combine them with array_combine().

So, how could I do a preg_split that addresses the problem of the first and final entry of the string? Is this way of doing it going to be too demanding on the server? Thank you for any help.

PS: I am using Drupal ApacheSolr to do this, which is why I need to split these up. They need to be sent to an object that is going to build q and qf differently for instance.

  • 写回答

3条回答 默认 最新

  • doulan2827 2014-01-18 20:57
    关注

    You don't need a regular expression to parse query strings. PHP already has a built-in function that does exactly this. Use parse_str():

    $str = 'q=Sugar Beet&qf=vegetables&range=time:[34-40]';
    parse_str($str, $params);
    print_r($params);
    

    Produces the output:

    Array
    (
        [q] => Sugar Beet
        [qf] => vegetables
        [range] => time:[34-40]
    )
    
    评论

报告相同问题?

悬赏问题

  • ¥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 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看