Change preg matchess with numbers

Viewed 40

I'm trying to replace the matches with numbers by sorting them but couldn't do it. I have a string that has {} in between words. I'd like to change them to 1, 2, 3, etc. without foreach. could be with preg matches all?

$string = 'sample {} test {} string {}';

This string must have seen like this: sample (0) test (1) string (2)

This is my code:

$string_split = explode('{}', $string);
foreach($string as $string_word){
  $i ++;
  echo $string_word . $i . ' ';
}
3 Answers

Another option using preg_replace_callback, incrementing the count for every replacement.

$string = 'sample {} test {} string {}';
$count = 0;
echo preg_replace_callback("~{}~", function($m) use (&$count) {
    return '(' . $count++ . ')';
}, $string);

Output

sample (0) test (1) string (2)

Php demo

You could iterate over your string using preg_match, keeping a counter along the way:

$string = 'sample {} test {} string {}';
$counter = 0;
while (preg_match("/\{\}/", $string)) {
    $string = preg_replace("/\{\}/", "(" . $counter . ")", $string, 1);
    $counter = $counter + 1;
}

echo "\n" . $string;

This prints:

sample {} test {} string {}
sample (0) test (1) string (2)

I was thinking the regex can be useful.

$re = '/(.*?)\s{}(\s?)/m';
$str = 'sample {} test {} string {}';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

// Print the entire match result

$new_string = null;
$i = 0;

foreach($matches as $item){
    $new_string .=  $item[1] . ' ('. $i . ') ';
    $i++;
}

echo $new_string;

Output:

sample (0) test (1) string (2) 
Related