如何在方括号(PHP)中的字符串中拆分数组?

时间:2015-12-03 09:44:31

标签: php arrays regex string explode

表单信息是此字符串[1,1x,1x,1x][2,2x,2x,2x]这是两个rownumbers。

这适用于PHP 5.4+我有5.2:

$str = "[1,1x,1x,1x][2,2x,2x,2x]";
$arr = [];
preg_replace_callback('/\[(.*?)\]/', function($m) use (&$arr){
    $arr[] = explode(',',preg_replace('/([\w]+)/', "[$1]", $m[1]));
}, $str);

这是输出:

Array {

  [0]=>Array {
      [0]=> "[1]" //rownumber
      [1]=> "[1x]"
      [2]=> "[1x]"
      [3]=> "[1x]"
  }
  [1]=>Array {
      [0]=> "[2]" //rownumber
      [1]=> "[2x]"
      [2]=> "[2x]"
      [3]=> "[2x]"
  }
  //etc
  [3]=>Array {
      [0]=> "[3]" //rownumber
      [1]=> "[3x]"
      [2]=> "[3x]"
      [3]=> "[3x]"
  }

}

Working demo

1 个答案:

答案 0 :(得分:0)

您只需使用preg_replace_callbackexplode就像

一样
$str = "[1,1x,1x,1x][2,2x,2x,2x]";
$arr = [];
preg_replace_callback('/\[(.*?)\]/', function($m) use (&$arr){
    $arr[] = explode(',',preg_replace('/([\w]+)/', "[$1]", $m[1]));
}, $str);

Working Demo