3v4l.org

run code in 300+ PHP versions simultaneously
<?php $originalString = "Hello world, what do you think of today's weather"; $findString = ' '; $nthOccurrence = 8; $newWord = ' beautiful '; function replaceNth(string $input, string $find, string $replacement, int $nth = 1): string { $pattern = '/(?:.*?\K' . preg_quote($find, '/') . '){' . $nth . '}/'; return preg_replace($pattern, $replacement, $input, 1); } echo replaceNth($originalString, $findString, $newWord, $nthOccurrence);

preferences:
28.28 ms | 405 KiB | 5 Q