<?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);
You have javascript disabled. You will not be able to edit any code.