dongrou2920 2016-07-29 09:12
浏览 45
已采纳

将字符串拆分为数组正则表达式php

I need to split the string bellow into array keys like in this format:

string = "(731) some text here with number 2 (220) some 54 number other text here" convert into:

array( 
  '731' => 'some text here with number 2', 
  '220' => 'some 54 number other text here' 
);

I have tried:

preg_split( '/\([0-9]{3}\)/', $string ); 

and got:

array ( 
  0 => 'some text here', 
  1 => 'some other text here' 
); 
  • 写回答

6条回答 默认 最新

  • dongpang2029 2016-07-29 10:38
    关注

    Code

    $string = "(731) some text here with number 2 (220) some 54 number other text here";
    
    preg_match_all("/\((\d{3})\) *([^( ]*(?> +[^( ]+)*)/", $string, $matches);
    $result = array_combine($matches[1], $matches[2]);
    
    var_dump($result);
    

    Output

    array(2) {
      [731]=>
      string(28) "some text here with number 2"
      [220]=>
      string(30) "some 54 number other text here"
    }
    

    <kbd>ideone demo</kbd>


    Description

    The regex uses

    • \((\d{3})\) to match 3 digits in parentheses and captures it (group 1)
    • \ * to match the spaces in between keys and values
    • ([^( ]*(?> +[^( ]+)*) to match everything except a ( and captures it (group 2)
      This subpattern matches exactly the same as [^(]*(?<! ) but more efficiently, based on the unrolling-the-loop technique.

      *Notice though that I am interpreting a value field cannot have a ( within. If that is not the case, do tell and I will modify it accordingly.

    After that, we have $matches[1] with keys and $matches[2] with values. Using array_combine() we generate the desired array.

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

报告相同问题?

悬赏问题

  • ¥15 python点云生成mesh精度不够怎么办
  • ¥15 QT C++ 鼠标键盘通信
  • ¥15 改进Yolov8时添加的注意力模块在task.py里检测不到
  • ¥50 高维数据处理方法求指导
  • ¥100 数字取证课程 关于FAT文件系统的操作
  • ¥15 如何使用js实现打印时每页设置统一的标题
  • ¥15 安装TIA PortalV15.1报错
  • ¥15 能把水桶搬到饮水机的机械设计
  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器