如何排列字符串的一部分?

时间:2019-03-23 15:35:44

标签: php string

('A190001', '1'),['A190001'],('A190001', '2'),['A190002'],('A190001', '1'),['A190001'],('A190001', '3'),['A190003'],

如何像这样更改样品:

('A190001', '1'),('A190001', '2'),('A190001', '1'),('A190001', '3'),

还有这个?:

['A190001'],['A190002'],['A190001'],['A190003'],

1 个答案:

答案 0 :(得分:0)

您的问题不是很清楚,所以我想您想在分开的字符串中包含括号部分和括号部分:

$s = "('A190001', '1'),['A190001'],('A190001', '2'),['A190002'],('A190001', '1'),['A190001'],('A190001', '3'),['A190003']," ;

// split string on commas preceded with ')' or ']'
$delimiterPattern = "/(?<=\)|\]),/" ; 
$parts = preg_split($delimiterPattern, $s, -1, PREG_SPLIT_NO_EMPTY);

// put each kind of item in different arrays
$parenthesesParts = array_filter($parts, function ($p){return $p[0] == '(' ;}); // collect part that begins with '('
$bracketsParts = array_diff($parts, $parenthesesParts); // take all the remaining parts

// glue parts with commas between them
$p1 = implode(',', $parenthesesParts);
$p2 = implode(',', $bracketsParts);

echo $p1 ; // ('A190001', '1'),('A190001', '2'),('A190001', '1'),('A190001', '3')
echo $p2 ; // ['A190001'],['A190002'],['A190001'],['A190003']