Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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

PHP Features

Last updated: 11 October 2026