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