Nested Parentheses to Array using regex in PHP [duplicate]

拟墨画扇 提交于 2019-12-12 05:14:44

问题


Possible Duplicate:
Regular Expression to match outer brackets

I have a string of the following format:

(((aaa (bbb) ccc)(ddd (eee) fff) ggg)(hhh (iii) )(jjj (kkk) lll) mmm)(nnn (ooo) ppp)(qqq (rrr) sss)

It basically has 3 main parts:

(((aaa (bbb) ccc)(ddd (eee) fff) ggg)(hhh (iii) )(jjj (kkk) lll) mmm)

(nnn (ooo) ppp)

(qqq (rrr) sss)

I need the search expression to get the 3 parts in an array (ignoring any sub parentheses). Once that is done, I need another search expression to split the individual parts (only 2nd & 3rd):

(nnn (ooo) ppp) => nnn,ooo,ppp

Thanks


回答1:


This is how I think I would do it:

<?php

$string = '(((aaa (bbb) ccc)(ddd (eee) fff) ggg)(hhh (iii) )(jjj (kkk) lll) mmm)(nnn (ooo) ppp)(qqq (rrr) sss)';

function parse_string($input) {
    $len = strlen($input);
    $substrings = array();
    $paren_count = 0;
    $cur_string = '';
    for ($i = 0; $i < $len; $i++) {
        $char = $input[$i];
        if ($char == '(') {
            $paren_count += 1;
        } elseif ($char == ')') {
            $paren_count -= 1;
        }
        $cur_string .= $char;
        if ($paren_count == 0 && strlen($cur_string)) {
            $substrings[] = $cur_string;
            $cur_string = '';
        }
    }
    return $substrings;
}

function convert_str($input) {
    $search = array('(', ')', ' ');
    $replace = array('', '', ',');
    return str_replace($search, $replace, $input);
}


$parsed_string = parse_string($string);
echo convert_str($parsed_string[1]);

OUTPUT:

nnn,ooo,ppp

This is a type of state machine.



来源:https://stackoverflow.com/questions/10361562/nested-parentheses-to-array-using-regex-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!