ds19891231 2018-10-21 22:45
浏览 85
已采纳

基于PHP中的特定字符串创建数组

I have a problem, I would like to ask for this string:

[NAME: abc] [EMAIL: email@gm.com] [TIMEFRAME: 3 weeks] [BUDGET: 1000 dollars] [MESSAGE: bla bla bla]

Replace it with an array in the form:

array(
        'NAME'      => 'abc',
        'EMAIL'     => 'email@gm.com',
        'TIMEFRAME' => '3 weeks',
        'BUDGET'    => '1000 dollars',
        'MESSAGE'   => 'bla bla bla' );

I tried to do something like this:

$content = str_replace(array('[', ']'), '', '[NAME: abc] [EMAIL: email@gm.com] [TIMEFRAME: 3 weeks] [BUDGET: 1000 dollars] [MESSAGE: bla bla bla]');
preg_match_all('/[A-Z]+\:/', $content, $inputs);

I managed to pull out the "keys", but I do not know how to pull out their "values". Any ideas?

Thank you in advance for your help and I apologize for my English.

  • 写回答

1条回答 默认 最新

  • dpq755012465 2018-10-21 22:52
    关注

    You may use the following regex:

    '~\[(\w+):\s*([^][]*)]~'
    

    See the regex demo.

    Details

    • \[ - a [ char
    • (\w+) - Group 1: 1+ letters, digits or _
    • : - a colon
    • \s* - 0+whitespaces
    • ([^][]*) - Group 2: 0+ chars other than [ and ]
    • ] - a ] char.

    See the PHP demo:

    $s = "[NAME: abc] [EMAIL: cde] [TIMEFRAME: efg] [BUDGET: hij] [MESSAGE: klm]";
    if (preg_match_all('~\[(\w+):\s*([^][]*)]~', $s, $m)) {
        array_shift($m); // Removes whole match values from array
        print_r(array_combine($m[0], $m[1])); // Build the result with keys (Group 1) and values (Group 2)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型