0

I need to change many posts and edit the content so that ^(...) becomes x^{...}.

What I have so far:

    $regexpattern = "/\^\((.*?)\)/";
    $replaceregex = "^{\$1}";

    $content_new = preg_replace($regexpattern, $replaceregex, $content);

which works.

However, I realized that if there is a round bracket inside the round wrapping brackets, it fails.

Example:

this should be transformed a^(x²) and this b^(-(x²))

becomes:

this should be transformed a^{x²} and this b^{-(x²})

Needed:

this should be transformed a^(x²) and this b^{-(x²)}

How can I prevent this and only replace the last bracket? Or do we need to use PHP and explode the content with ^(...) into Arrays and replace?

It could also be that there are multiple brackets inside (even if rare).

PS: After writing this question I found: https://stackoverflow.com/a/27052437/1066234 but there is no solution provided for this specific case.

anubhava
  • 761,203
  • 64
  • 569
  • 643
Avatar
  • 14,622
  • 9
  • 119
  • 198

2 Answers2

1

You can use this recursive regex in PHP with a negative lookahead:

$str = 'this should be transformed a^(x²) and this b^(-(x²))';
$re = '/\^ ( \( ( (?: [^()]* | (?-2) )* ) \) ) (?!.*\^\()/x';
$repl = preg_replace($re, '^{$2}', $str);
//=> this should be transformed a^(x²) and this b^{-(x²)}

RegEx Demo

anubhava
  • 761,203
  • 64
  • 569
  • 643
1

Such regex matches only outter brackets

 \^(\((([^()]|(?1))*)\))

and replace with

^{$2}

demo on regex101

demo on sandbox

splash58
  • 26,043
  • 3
  • 22
  • 34