正则表达式将abcd转换为(a(b(c(d))))

Max*_*Max 3 php regex pcre preg-replace

我正在使用PHP的preg_replace,并尝试转换字符串

abcd

(a(b(c(d))))

这是我得到的最好的:

preg_replace('/.(?=(.*$))/', '$0($1)', 'abcd');
// a(bcd)b(cd)c(d)d()
Run Code Online (Sandbox Code Playgroud)

是否可以使用正则表达式?

编辑我刚刚在PCRE规范中发现了这个:Replacements are not subject to re-matching所以我原来的方法不会起作用.我想保留所有正则表达式,因为在我的实际用例中有一些更复杂的匹配逻辑.

rua*_*akh 6

怎么样:

preg_replace('/./s', '($0', 'abcd') . str_repeat(')', strlen('abcd'));
Run Code Online (Sandbox Code Playgroud)

(这算是"带正则表达式"吗?)