开发者

how to replace string from given offset?

开发者 https://www.devze.com 2023-01-21 06:33 出处:网络
I need only one replacement of a string within a string, but si开发者_如何学Pythonnce string that am intend to replace is repeated in the haystack I need to precise start pointer and how many times re

I need only one replacement of a string within a string, but si开发者_如何学Pythonnce string that am intend to replace is repeated in the haystack I need to precise start pointer and how many times replacement should be done. I did not found any mention of start offstet if php's string replace functions.


str_replace(substr($string,$start),$replace)


You can use substr, for instance :

$str = "This This This";
echo substr($str, 0, 6) . str_replace('This', 'That', substr($str, 6)); // This This That


You could use some other functions than str_replace that supports a limited search, for example preg_replace:

preg_replace('/'.preg_quote($search, '/').'/', $replacement, $str, 1)

Or a combination of explode and implode:

implode($replacement, explode($search, $str, 2))
0

精彩评论

暂无评论...
验证码 换一张
取 消