PHP regular expression to replace nested () with []

前端 未结 5 1366
感动是毒
感动是毒 2021-01-21 23:25

I am trying to match a string, see example, such that a nested parantheses () is replaced by [] so to not break a parser somewhere else. In this case, I would like to replace t

5条回答
  •  我在风中等你
    2021-01-22 00:08

    You could do this with a for loop and an array acting as a stack. When you find an open bracket, push onto the stack, and when you find a closing bracket pop from the stack. The length of the stack will tell you if you should replace the current bracket.

    $stack = array();
    $str = "Arman; Dario (10040 Druento (Turin), IT)";
    $out = "";
    
    for ($i = 0, $l = strlen($str); $i < $l; ++$i) {
        if ($str[$i] == "(") {
            $stack[] = true;
    
            if (count($stack) % 2) { // alternate between ( and [
                $out .= "(";
            } else {
                $out .= "[";
            }
        } else if ($str[$i] == ")") {
            if (count($stack) % 2) {
                $out .= ")";
            } else {
                $out .= "]";
            }
            array_pop($stack);
        } else {
            $out .= $str[$i];
        }
    }
    

    Here's some sample input and output:

    Arman; Dario (10040 Druento (Turin), IT)
    Arman; Dario (10040 Druento [Turin], IT)
    
    a ( b ( c ( d ) ) e )
    a ( b [ c ( d ) ] e )
    
    a (b  (c) (d) (e) )
    a (b  [c] [d] [e] )
    
    a (b (c (d) (e) (f)))
    a (b [c (d) (e) (f)])
    

    It's not a particularly efficient algorithm (building the string char by char), and it could be a bit smarter about unmatched brackets, but anyway...

提交回复
热议问题