PHP preg_replace_callback,只替换 1 个反向引用? [英] PHP preg_replace_callback, replace only 1 backreference?
问题描述
使用preg_replace_callback
,是否可以只替换一个反向引用?还是我必须退回整个东西?
Using preg_replace_callback
, is it possible to replace only one backreference? Or do I have to return the entire thing?
我只是想用引号将令牌的默认值包装起来.
I'm just trying to wrap the token's default value with quotes.
$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);
我是否必须获取更多的反向引用,以便我能够构建一个新版本的令牌并返回它,我不能只替换反向引用 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? Thanks.
推荐答案
我是否必须获取更多的反向引用才能构建新版本的令牌并返回,我不能只替换反向引用 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?
您有两个选择:
- 如您所说,使用额外的反向引用来构造替换字符串,或者
- 使用环视仅匹配您要替换的部分.
通常我建议使用第一种方法,因为第二种方法效率较低,并且在某些情况下可能导致无效匹配(当前瞻和后向可能重叠时).在这种情况下,就没有问题了.
Usually I recommend using the first approach as the second is a bit less efficient and can lead to invalid matches in some cases (when the lookahead and behind can overlap). In this case there would be no problem tho.
第二个选项的示例是:
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).(?=})
是一个前瞻,表示以下必须是}
但不包括它自己的匹配.\K
is a way to exclude everything before it from the actual match (like if we had a variable length lookbehind there).(?=})
is a lookahead, saying that the following has to be a}
but does not include it in the match it self.
这篇关于PHP preg_replace_callback,只替换 1 个反向引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!