dongwo5589 2016-04-30 11:25
浏览 31
已采纳

PHP括号内容索引在数组中

I want to take the string:

(contents) some text (contents two) more text 

and have it output this array:

array(

[contents] => some text
[contents two] => more text

)

I've tried looping thru it and using array_push

  • 写回答

3条回答 默认 最新

  • duansanzi5265 2016-04-30 11:43
    关注

    The solution using preg_match_all(with named submasks (?<name>)) and array_combine functions:

    $str = '(contents) some text (contents two) more text';
    
    preg_match_all("/\((?<key>.+?)\) (?<value>[^()]+)/iu", $str, $m, PREG_PATTERN_ORDER);
    $result = array_combine($m['key'], $m['value']);
    
    print_r($result);
    

    The output:

    Array
    (
        [contents] => some text 
        [contents two] => more text
    )
    

    Update: For your additional request "make it work if there's no space after the bracket" with the input string "(contents)some text (contents two)more text" : to make it work - change the current regex pattern to as following "/\((?<key>.+?)\)\s?(?<value>[^()]+)/iu"

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

报告相同问题?

悬赏问题

  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像