Search code examples
phparrayspreg-replacepreg-matchpreg-replace-callback

update the string and preserve old data in array


I'm curious if it is possible to make this piece of code I've made a bit shorter and probably faster? The goal of this code below is to update the string by changing (and preserving) numbers in it with ordered replacements such as {#0}, {#1} and so on for each number found.

Also, keep that found numbers separately in array so we may recover information at any time.

The code below works but I believe it may be significantly optimized and hopefully done in one step.

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

Is it possible?


Solution

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

    After some little fixes it works. \d+ works too.

    NOTE: Can not explain why global $nums; wont work. Maybe php internal issue/bug