PHP preg_replace_callback,仅替换 1 个反向引用?

标签 php regex string replace

使用preg_replace_callback,是否可以只替换一个反向引用?还是我必须退回整件东西?

我只是想用引号将 token 的默认值括起来。

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

我是否必须获取更多反向引用才能构建新版本的 token 并返回它,我不能只替换反向引用 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?

你有两个选择:

  1. 如您所说,使用额外的反向引用来构造替换字符串,或者
  2. 使用环视仅匹配您要替换的部分。

通常我建议使用第一种方法,因为第二种方法效率较低,并且在某些情况下会导致无效匹配(当先行和后行可以重叠时)。在这种情况下不会有问题。

第二个选项的例子是:

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)。
  • (?=}) 是前瞻性的,表示以下必须是 但不将其包含在匹配项中。

关于PHP preg_replace_callback,仅替换 1 个反向引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11960584/

相关文章:

php - 从php以特定用户身份执行bat文件

c - 在 C 中解析/匹配字符串出现

regex - 使用正则表达式仅提取全部大写单词

regex - 匹配正则字符串

android - 如何在android textview中显示API级别的硬编码字符串

html 表格行中或数据库本身中的 PHP 方程

java - 从服务器接收响应时出错?

php - Eloquent 中的外键关系不起作用

c++ - %[^\n] 在 scanf() 格式字符串中是什么意思

字符串匹配算法