How can I keep track of the current match’s offset from the start of the string in the callback of preg_replace_callback
?
For example, in this code, I’d like to point to the location of the match that throws the exception:
$substituted = preg_replace_callback('/{([a-z]+)}/', function ($match) use ($vars) {
$name = $match[1];
if (isset($vars[$name])) {
return $vars[$name];
}
$offset = /* ? */;
throw new Exception("undefined variable $name at byte $offset of template");
}, $template);