Try something like this:
$text = "stop [chomping [too] early] here!";
$text =~ s/[([^[]]|(?0))*]//g;
print($text);
which will print:
stop here!
A short explanation:
[ # match '['
( # start group 1
[^[]] # match any char except '[' and ']'
| # OR
(?0) # recursively match group 0 (the entire pattern!)
)* # end group 1 and repeat it zero or more times
] # match ']'
The regex above will get replaced with an empty string.
You can test it online: http://ideone.com/tps8t
EDIT
As @ridgerunner mentioned, you can make the regex more efficiently by making the *
and the character class [^[]]
match once or more and make it possessive, and even by making a non capturing group from group 1:
[(?:[^[]]++|(?0))*+]
But a real improvement in speed might only be noticeable when working with large strings (you can test it, of course!).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…