Question

Given some text I want remove all text wrapped between { and }. The block may themselves contain some block. How can I do that using PCRE regex?

\\example input:
{a}b{c{d}}e{f{g}h}

\\output:
be
Was it helpful?

Solution

Using regular expression recursion:

\{(?>[^{}]|(?R))*\}

See a regex101 demo


PHP example:

$input = '{a}b{c{d}}e{f{g}h}';
$output = preg_replace('/\{(?>[^{}]|(?R))*\}/', '', $input);
echo($output); # => be
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top