This may be obvious to others, but I just spent hours and my feeble brain only caught up to it after a long break.
If you are looping through a string which has multiple substrings that need to be replaced, you have to add an offset factor to each original offset before you replaced any strings. Here is a real world example:
From draft.js we get paragraphs with multiple links designated only with offset, anchor text length, url, target. So each anchor text must be wrapped in the anchortext to save proper content in the database.
Here is the implementation of offset factor:
$offset_factor = 0;
foreach($content->links->links as $index=>$link){
$replacement = ''.$link->anchorText.'';
$new_offset = $link->offset + $offset_factor;
$newtext = \substr_replace($content->text, $replacement, $new_offset, $link->length);
//now we reset the original paragraph text with newtext
$content->text = $newtext;
//calculate the new offset by calculating the difference in replacement length and original length and add that to the offset_factor
$additional_characters = strlen($replacement) - $link->length;
$offset_factor = $offset_factor + $additional_characters;
}
I hope this helps a noobie :) If there is another easier way, I would love to hear about it.