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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。