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)
棘手的部分是它需要尽可能以速度和内存使用的最佳方式完成.
遗漏的是这样的:
$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是指第一个(也是唯一一个)捕获组捕获的字符串.
$code = preg_replace('/\{(\d+)\}/', 'test($1)', $code);
Run Code Online (Sandbox Code Playgroud)
根据我的经验,preg_replace是很多不是用做替代品的任何方法快str_replace或strtr.
| 归档时间: |
|
| 查看次数: |
9776 次 |
| 最近记录: |