我能以某种方式知道在 preg_replace_callback 的回调中正在发生哪个替换吗?

发布于 2024-08-26 02:34:16 字数 393 浏览 5 评论 0原文

我使用 preg_replace_callback 来替换字符串中的特定标记。但除了实际的标记之外,我还需要知道该标记是主题字符串中的第一个、第二个还是第三个。有什么方法可以访问该信息吗?

我在 preg_replace_callback 定义中发现了一个参数 $count (http://php.net/manual/en/function.preg-replace-callback.php),它计算替换次数,但我不确定是否可以从回调中访问它。在所描述的上下文中是否有任何用法示例?

I'm using preg_replace_callback to substitute particular tokens within the string. But apart from actual token I need to know as well whether that token was first, second or third in a subject string. Is there any way to access that info?

I found an argument $count in preg_replace_callback definition (http://php.net/manual/en/function.preg-replace-callback.php), which counts replacements, but I'm not sure if it is accessible from within callback. Any example of the usage in described context?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

别挽留 2024-09-02 02:34:16

$count out 变量仅在所有替换完成后设置。相反,尝试使用静态变量:

function repl($matches) {
    static $count = 0;
    ++$count;
    ...
}
preg_replace_callback('/.../', 'repl', $haystack);

The $count out variable is only set after all the replacements are done. Instead, try a static variable:

function repl($matches) {
    static $count = 0;
    ++$count;
    ...
}
preg_replace_callback('/.../', 'repl', $haystack);
七禾 2024-09-02 02:34:16

您始终可以创建一个非局部变量来保存计数。

You can always create a non-local variable to keep the count.

柒七 2024-09-02 02:34:16

在 php 5.3+ 中,您还可以使用 closure (而不是全局或静态变量)

$counter = 0
preg_replace_callback('/.../', function($matches) use(&$counter) {
  ++$counter;
  ...
  },  $haystack
);

With php 5.3+ you can also use a closure (instead of a global or static variable)

$counter = 0
preg_replace_callback('/.../', function($matches) use(&$counter) {
  ++$counter;
  ...
  },  $haystack
);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文