Can your text contain [
?
If not you can use something in the spirit of
((?:\s*\[[^\]]+\])*)([^[]+)((?:\[[^\]]+\]\s*)*)
( # first capturing group
(?: # non capturing group
\s* # might be whitespaces
\[ # opening [
[^\]]+ # anything except a closing ]
\] # closing ]
)* # zero or more times
)
([^[]+) # store in second capturing group any string that doesn't contain a [
((?:\[[^\]]+\]\s*)*) # catch tags in capture group 3
and replace it with
$1[text_box text="$2"][/textbox]$3
The idea is to catch the text that doesn't contain a [
. When we stop, we know the next character will a [
, so this is a tag, so we catch every consecutive [...]
tags. Afterwards it's text again, so we reapply the pattern.
The "tag capture" before the text will only be used once, if the string starts with tags.
See demo here