更新字符串并保留数组中的旧数据

update the string and preserve old data in array

我很好奇是否可以让我编写的这段代码更短一些并且可能更快一些?下面这段代码的目标是通过更改(并保留)其中的数字来更新字符串,并为找到的每个数字使用 {#0}、{#1} 等有序替换。

此外,将找到的数字单独保存在数组中,以便我们随时恢复信息。

下面的代码有效,但我相信它可能会得到显着优化,并有望一步完成。

$str = "Lnlhkjfs7834hfdhrf87whf4akuhf999re";//could be any string

$nums = array();
$count = 0;

$res = preg_replace_callback('/\d+/', function($match) use(&$count) {
    global $nums;
    $nums[] = $match[0];
    return "{#".($count++)."}";
}, $str);

print_r($str); // "Lnlhkjfs7834hfdhrf87whf4akuhf999re"

print_r($res); // "Lnlhkjfs{#0}hfdhrf{#1}whf{#2}akuhf{#3}re"

print_r($nums); // ( [0] => 7834    [1] => 87    [2] => 4    [3] => 999 )

可能吗?

  $str = "Lnlhkjfs7834hfdhrf87whf4akuhf999re";//could be any string

  $nums = array();
  $count = 0;

  $res = preg_replace_callback('/([0-9]+)/', function($match) use (&$count,&$nums) {
      $nums[] = $match[0];
      return "{#".($count++)."}";
  }, $str);

  print_r($str); // "Lnlhkjfs7834hfdhrf87whf4akuhf999re"

  print_r($res); // "Lnlhkjfs{#0}hfdhrf{#1}whf{#2}akuhf{#3}re"

  print_r($nums); // ( [0] => 7834    [1] => 87    [2] => 4    [3] => 999 )

经过一些小的修复后它可以工作了。 \d+ 也有效。

注意:无法解释为什么 global $nums; 不起作用。也许 php 内部 issue/bug

没有什么可以添加到@JustOnUnderMillions 的答案中,只是另一种避免回调函数的方法:

$nums = [];

$res = preg_split('~([0-9]+)~', $str, -1, PREG_SPLIT_DELIM_CAPTURE);

foreach ($res as $k => &$v) {
    if ( $k & 1 ) {
        $nums[] = $v;
        $v = '{#' . ($k >> 1) . '}';
    }
}

$res = implode('', $res);

不是更短,而是更快。