note 125126 added to function.substr-replace

From: Date: Thu, 18 Jun 2020 16:47:50 +0000
Subject: note 125126 added to function.substr-replace
Groups: php.notes 
Request: Send a blank email to php-notes+get-214777@lists.php.net to get a copy of this message
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 <a href="url" target="target">anchortext</a> 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 = '<a href="'.$link->href.'" target="$link->target">'.$link->anchorText.'</a>'; $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. ---- Server IP: 45.112.84.4 Probable Submitter: 103.51.166.36 (proxied: 2600:6c60:4a00:f4:e42a:8534:dab0:3569) ---- Manual Page -- http://php.net/manual/en/function.substr-replace.php Edit -- https://master.php.net/note/edit/125126 Del: integrated -- https://master.php.net/note/delete/125126/integrated Del: useless -- https://master.php.net/note/delete/125126/useless Del: bad code -- https://master.php.net/note/delete/125126/bad+code Del: spam -- https://master.php.net/note/delete/125126/spam Del: non-english -- https://master.php.net/note/delete/125126/non-english Del: in docs -- https://master.php.net/note/delete/125126/in+docs Del: other reasons-- https://master.php.net/note/delete/125126 Reject -- https://master.php.net/note/reject/125126 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#214777) next »