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

时间:2017-02-17 16:55:35

标签: php arrays preg-replace preg-match preg-replace-callback

我很好奇是否有可能制作这段代码我做得更短,可能更快?下面这段代码的目标是通过更改(和保留)其中的数字来更新字符串,并为每个找到的数字添加{#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 )

有可能吗?

2 个答案:

答案 0 :(得分:2)

  $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内部问题/ bug

答案 1 :(得分:1)

没有什么可以添加到@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);

不短,但更快。