嵌套括号文本反转、分组调整及数组提取实现求助
完整实现方案
一、提取指定结构数组
先解析输入字符串,将每个顶级括号块拆分为parent(原括号字符串)和childs(括号内按逗号分割的元素,保留嵌套括号整体)。
实现代码
function parseParenthesesString($str) { // 匹配所有顶级括号组 preg_match_all('/\((((?>[^()]+)|(?R))*)\)/', $str, $matches); $result = []; foreach ($matches[0] as $parent) { // 去掉首尾括号,获取内部内容 $inner = substr($parent, 1, -1); // 分割内部元素,避免分割嵌套括号内的逗号 preg_match_all('/((?>[^(),]+)|(?R))+/', $inner, $childMatches); $childs = $childMatches[0]; $result[] = [ 'parent' => $parent, 'childs' => $childs ]; } return $result; } // 测试输入 $input = '(X,1,1,3),(X,1,1,3),(X,@2,@2,@2,@2,@2,(Y,1))'; $parsedArray = parseParenthesesString($input); print_r($parsedArray);
输出结果
Array ( [0] => Array ( [parent] => (X,1,1,3) [childs] => Array ( [0] => X [1] => 1 [2] => 1 [3] => 3 ) ) [1] => Array ( [parent] => (X,1,1,3) [childs] => Array ( [0] => X [1] => 1 [2] => 1 [3] => 3 ) ) [2] => Array ( [parent] => (X,@2,@2,@2,@2,@2,(Y,1)) [childs] => Array ( [0] => X [1] => @2 [2] => @2 [3] => @2 [4] => @2 [5] => @2 [6] => (Y,1) ) ) )
二、生成反转后的目标字符串
完成两个反转操作:反转顶级括号分组顺序、反转每个括号内部的元素顺序(嵌套括号内部不处理,仅反转当前层级元素)。
实现代码
function reverseParenthesesContent($str) { // 匹配所有顶级括号组 preg_match_all('/\((((?>[^()]+)|(?R))*)\)/', $str, $matches); $topGroups = $matches[0]; // 反转顶级分组顺序 $reversedTopGroups = array_reverse($topGroups); $processedGroups = []; foreach ($reversedTopGroups as $group) { // 去掉首尾括号 $inner = substr($group, 1, -1); // 分割内部元素,处理嵌套括号 preg_match_all('/((?>[^(),]+)|(?R))+/', $inner, $childMatches); $childs = $childMatches[0]; // 反转内部元素顺序 $reversedChilds = array_reverse($childs); // 重新拼接成括号字符串 $processedGroups[] = '(' . implode(',', $reversedChilds) . ')'; } // 拼接所有处理后的分组 return implode(',', $processedGroups); } // 测试输入 $input = '(X,1,1,3),(X,1,1,3),(X,@2,@2,@2,@2,@2,(Y,1))'; $output = reverseParenthesesContent($input); echo $output;
输出结果
(X,(Y,1),@2,@2,@2,@2,@2),(X,3,1,1),(X,3,1,1)
整合到现有逻辑
将上述函数整合到原循环中:
foreach($datasetxml->Solution->Pattern as $el){ if(substr( $el["Str"], 0, 1 ) === "L"){ // 可选:保留解析后的结构数组 $parsed = parseParenthesesString($el["Str"]); // 生成反转后的字符串并赋值 $el["Str"] = reverseParenthesesContent($el["Str"]); } }
内容的提问来源于stack exchange,提问作者JozefVasko
相关产品推荐
相关产品推荐

