在preg_replace_callback()回调函数中访问当前匹配的偏移量


Access the offset of the current match in the callback function of preg_replace_callback()

如何在preg_replace_callback的回调中跟踪当前匹配的偏移量?

例如,在这段代码中,我想指出引发异常的匹配的位置:

$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);

由于标记的答案不再可用,以下是为我获得当前替换索引的方法:

$index = 0;
preg_replace_callback($pattern, function($matches) use (&$index){
    $index++;
}, $content);

正如你所看到的,我们必须自己维护索引,使用超出作用域的变量

可以先匹配preg_match_all &PREG_OFFSET_CAPTURE选项并重建您的字符串,而不是使用默认的preg_replace方法。

从PHP 7.4.0开始,preg_replace_callback也接受PREG_OFFSET_CAPTURE标志,将每个匹配组转换为[text, offset]对:

$substituted = preg_replace_callback('/{([a-z]+)}/', function ($match) use ($vars) {
    $name = $match[1][0];
    if (isset($vars[$name])) {
        return $vars[$name];
    }
    $offset = $match[0][1];
    throw new Exception("undefined variable $name at byte $offset of template");
}, $template, flags: PREG_OFFSET_CAPTURE);