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
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.static counter declaration will only set $counter to 0 on the first visit.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
);