Replacing a sequence in a row with a matching index

In PHP, if I replace "a" in the string "ababab c", how do I replace it with a matching index (i.e., "1 b 2 b 3 b c")?

+3
source share
3 answers
$str = 'a b a ba a';
$count = 1;
while(($letter_pos = strpos($str, 'a')) !== false) {
    $str = substr_replace($str, $count++, $letter_pos, 1);
}
+2
source

use preg_replace_callbackinstead.

PHP 5.3.0 example (not verified):

$i = 0;
preg_replace_callback("/a/", function( $match ) {
    global $i;
    return ++$i;
}, "a b a b a b c");
+2
source

, preg _ *?

:

$numerals = range(1, 10);
$str = str_replace('a', $numerals, $str);

str_replace() . , , .

+2

Source: https://habr.com/ru/post/1781417/


All Articles