douchan7552 2018-09-27 10:09
浏览 171
已采纳

如何从输入字符串创建包含键值对的数组数组?

I am developing a search bar in php, but can't write a regex expression that can do what I require.

I have an input string like this:

$text = "key1=value 1 key2=value 2 key3=val 3";

I would like to be able to split into a multi-dimensional array with this structure:

$array = [["key1", "value 1"], ["key2", "value 2"], ["key3", "val 3"]];

How can this be done with a regex pattern in php?

  • 写回答

3条回答 默认 最新

  • douqiaolong0528 2018-10-02 14:05
    关注

    Here are two ways to generate your desired multidimensional array of key-value pairs with preg_split()...

    (Demo)

    Approach #1: Split on = or space followed by 1 or more word characters then a =

    var_export(array_chunk(preg_split('~=| (?=\w+=)~', $text), 2));
    

    Approach #2: Split on each key, include leading&training characters in match, retain only keys & values

    var_export(array_chunk(preg_split('~ ?(\w+)=~', $text, null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE), 2));
    

    Output: (from either)

    array (
      0 => 
      array (
        0 => 'key1',
        1 => 'value 1',
      ),
      1 => 
      array (
        0 => 'key2',
        1 => 'value 2',
      ),
      2 => 
      array (
        0 => 'key3',
        1 => 'val 3',
      ),
    )
    

    preg_split() can only return a single dimensional array (in this case, key, val, key, val, ...), so array_chunk() is used to generate the desired two-elements-per-subarray structure.

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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器