PHP preg_replace_callback, replace only 1 backreference?

后端 未结 3 2031
一个人的身影
一个人的身影 2021-01-20 05:12

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 tok

3条回答
  •  旧时难觅i
    2021-01-20 06:10

    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?

    You have two options:

    1. Use extra backreferences to construct the replacement string, as you said, or
    2. use lookarounds to only match the part you want to replace.

    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.

    Example of the second option would be:

    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 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.

提交回复
热议问题