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
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...