使用preg_replace_callback
,是否可以只替换一个反向引用?还是我必须退回整件东西?
我只是想用引号将 token 的默认值括起来。
$str = 'This is a {$token|token was empty}';
$str = preg_replace_callback('~{\$\w+\|(.*)?}~i', function($match) {
//$match[1] is "token was empty"
//I want to just replace $match[1], but it needs me to return the whole thing
}, $str);
我是否必须获取更多反向引用才能构建新版本的 token 并返回它,我不能只替换反向引用 1?谢谢。
最佳答案
Do I have to grab more backreferences so I'm able to build out a new version of the token and return that, I can't just replace backreference 1?
你有两个选择:
- 如您所说,使用额外的反向引用来构造替换字符串,或者
- 使用环视仅匹配您要替换的部分。
通常我建议使用第一种方法,因为第二种方法效率较低,并且在某些情况下会导致无效匹配(当先行和后行可以重叠时)。在这种情况下不会有问题。
第二个选项的例子是:
preg_replace_callback('~{\$\w+\|\K(?:[^{}]+)?(?=})~i', function($match){
// $match[0] contains what used to be the first capturing group.
// return the value you want to replace it with
// (you can still use the capturing group if you want, but it's unnecessary)
});
\K
是一种从实际匹配中排除它之前的所有内容的方法(就像我们在那里有一个可变长度的 lookbehind)。(?=})
是前瞻性的,表示以下必须是但不将其包含在匹配项中。
关于PHP preg_replace_callback,仅替换 1 个反向引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11960584/