preg_replace_callback 中的闭包问题

发布于 2024-10-08 13:58:36 字数 597 浏览 0 评论 0原文

该脚本检查某些文本的每一行是否有“FIRST”和“LAST”单词,并尝试用 $temp_names 数组中的条目替换它们。

$temp_names = array('FIRST' => array('John','Jack'),'LAST' => array('Doe','Smith'));

for ($i=0; $i < count($lines); $i++)
{ 
  $lines[$i] = preg_replace_callback("/FIRST|LAST/",
                                        function($matches) use ($temp_names){ 
                                        return array_shift($temp_names[$matches[0]]); }, $lines[$i]);

}

我在闭包函数中遇到 return array_shift() 问题。它正确返回第一个条目,但该条目保留在数组中。所以每次它都会返回“John”和“Doe”。这是为什么?

谢谢。

This script check every line of some text for "FIRST" and "LAST" words, and trying to replace them by entries in $temp_names array.

$temp_names = array('FIRST' => array('John','Jack'),'LAST' => array('Doe','Smith'));

for ($i=0; $i < count($lines); $i++)
{ 
  $lines[$i] = preg_replace_callback("/FIRST|LAST/",
                                        function($matches) use ($temp_names){ 
                                        return array_shift($temp_names[$matches[0]]); }, $lines[$i]);

}

i have problem with return array_shift() in closure function. It correctly returns the first entry, but the entry stays in array. So every time it return "John" and "Doe". Why is that?

thanks.

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

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

发布评论

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

评论(1

╭⌒浅淡时光〆 2024-10-15 13:58:36

为了对 $temp_names 数组进行任何更改(例如移动值),您需要通过引用来使用它,例如

function ($matches) use (&$temp_names) 

In order to have any changes to the $temp_names array (such as shifting a value), you need to use it by reference like

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