php 字符串 replace,PHP: substr_replace - Manual

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值