Replace The n-th In A String
<?php
$string = "An elephant is an elephant";
print str_replace('ph', 'php', $string);
print PHP_EOL;
$closure = function() {
static $count = 0;
++$count;
return $count === 2 ? 'php' : 'ph';
};
print preg_replace_callback('/ph/', $closure, $string);
print PHP_EOL;
$pos1 = strpos($string, 'ph');
$pos2 = strpos($string, 'ph', $pos1 + 3);
print substr_replace($string, 'php', $pos2, strlen('ph'));
Replacing the n-th string in a longer string is trickier than for the first. In particular, the explode() trick won’t work, and so will preg_replace(), with its limit.
This time, we need to use preg_replace_callback(), which allows a closure to be executed to calculate the replacement string. Here, with a counter, we can replace the desired string.
Another solution is to locate the position, and use substr_replace(), which accepts a limit and an offset.
See Also
- Replacing the n-th [Try me]
PHP Features
Last updated: 11 October 2026