正则表达式匹配"{number}"

Chr*_*ian 5 php regex performance

我需要将"{Z}"替换为"test(Z)",其中Z始终是使用PHP和正则表达式的无符号整数(除非有更快的方法?).

$code='{45} == {2}->val() - {5}->val()';
// apply regex to $code
echo $code;
// writes: test(45) == test(2)->val() - test(5)->val()
Run Code Online (Sandbox Code Playgroud)

棘手的部分是它需要尽可能以速度和内存使用的最佳方式完成.

Mar*_*ers 8

遗漏的是这样的:

$code = preg_replace('/{([0-9]+)}/', 'test($1)', $code);
Run Code Online (Sandbox Code Playgroud)

这个怎么运作:

{       match a literal {
(       start a capturing group
[0-9]+  one or more digits in 0-9
)       end the capturing group
}       match a literal }

替换字符串中的$ 1是指第一个(也是唯一一个)捕获组捕获的字符串.

  • 使用`\ d`; 我们不要开始教导坏习惯. (4认同)

amp*_*ine 5

$code = preg_replace('/\{(\d+)\}/', 'test($1)', $code);
Run Code Online (Sandbox Code Playgroud)

根据我的经验,preg_replace很多不是用做替代品的任何方法快str_replacestrtr.