Michdd Posted May 17, 2009 Share Posted May 17, 2009 Is it possible to make str_replace only replace the first X occurrences? Link to comment https://forums.phpfreaks.com/topic/158456-str_replace-only-x-times/ Share on other sites More sharing options...
Ken2k7 Posted May 17, 2009 Share Posted May 17, 2009 Find out - str_replace Link to comment https://forums.phpfreaks.com/topic/158456-str_replace-only-x-times/#findComment-835668 Share on other sites More sharing options...
Michdd Posted May 17, 2009 Author Share Posted May 17, 2009 Find out - str_replace I've already read that. I know with the function itself it isn't possible.. What I meant was.. what would be a good way to use str_replace, but set it up so that it only replaces the first X occurrences Link to comment https://forums.phpfreaks.com/topic/158456-str_replace-only-x-times/#findComment-835675 Share on other sites More sharing options...
Ken2k7 Posted May 17, 2009 Share Posted May 17, 2009 Sorry, I meant substr_replace. You can use that, but I would use combo explode and implode. Link to comment https://forums.phpfreaks.com/topic/158456-str_replace-only-x-times/#findComment-835688 Share on other sites More sharing options...
thebadbad Posted May 17, 2009 Share Posted May 17, 2009 Or if you don't mind starting the RegEx engine, preg_replace() has a limit parameter. Link to comment https://forums.phpfreaks.com/topic/158456-str_replace-only-x-times/#findComment-835719 Share on other sites More sharing options...
Daniel0 Posted May 17, 2009 Share Posted May 17, 2009 function str_replace_count($search, $replace, $subject, $limit) { for ($i = 0, $replaceLength = strlen($replace); $i < $limit && ($pos = strpos($subject, $search)) !== false; $i++) { $subject = substr_replace($subject, $replace, $pos, $replaceLength); } return $subject; } $string = 'foo foo foo foo foo foo foo'; echo str_replace_count('foo', 'bar', $string, 3); // bar bar bar foo foo foo foo Link to comment https://forums.phpfreaks.com/topic/158456-str_replace-only-x-times/#findComment-835731 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.