Search code examples
phpcounterincrementstr-replacestart-of-line

Replace substrings with an incremented counter value


Basically what I'm looking for is the PHP version of this thread: Find, replace, and increment at each occurence of string

I would like to replace the keyword following > at the start of rach line with an incrementing counter.

If my input is:

>num, blah, blah, blah

ATCGACTGAATCGA

>num, blah, blah, blah

ATCGATCGATCGATCG

>num, blah, blah, blah

ATCGATCGATCGATCG

I would like it to be...

>0, blah, blah, blah

ATCGACTGAATCGA

>1, blah, blah, blah

ATCGATCGATCGATCG

>2, blah, blah, blah

ATCGATCGATCGATCG

Solution

  • $str = 'a hello a some a';
    $i = 0;
    
    while (strpos($str, 'a') !== false)
    {
        $str = preg_replace('/a/', $i++, $str, 1);
    }
    
    echo $str;