Jump to content

str_replace(), only X times?


Michdd

Recommended Posts

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.