Replace substrings with an incremented counter value

后端 未结 5 1933
耶瑟儿~
耶瑟儿~ 2021-01-17 08:25

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 follow

5条回答
  •  忘掉有多难
    2021-01-17 09:05

    I prefer to use preg_replace_callback() for this task . It is a more direct solution than making iterated single preg_replace() calls which restart from the beginning of the string each time (checking text that has already been replaced).

    • ^ means the start of a line because of the m pattern modifier.
    • \K means restart the full string match. This effectively prevents the literal > from being replaced and so only the literal string num is replaced.
    • the static counter declaration will only set $counter to 0 on the first visit.
    • the custom function does not need to receive the matched substring because the entire full string match is to be replaced.

    Code: (Demo)

    $text = <<num, blah, blah, blah
    
    ATCGACTGAATCGA
    
    >num, blah, blah, blah
    
    ATCGATCGATCGATCG
    
    >num, blah, blah, blah
    
    ATCGATCGATCGATCG
    TEXT;
    
    echo preg_replace_callback(
             "~^>\Knum~m",
             function () {
                 static $counter = 0;
                 return ++$counter;
             },
             $text
         );
    

提交回复
热议问题