function moveNthWordToEndOfString(string $input, int $n): string
{
if (trim($input) === '') {
return $input;
}
// Split on whitespace, remove empty pieces
$parts = preg_split('/\s+/', $input, -1, PREG_SPLIT_NO_EMPTY);
if ($n < 0 || $n >= count($parts)) {
throw new OutOfRangeException("Index $n is out of range.");
}
$word = $parts[$n];
unset($parts[$n]);
// Reindex array to avoid gaps
$parts = array_values($parts);
$parts[] = $word;
return implode(' ', $parts);
}
$s = "Would you like to know more? (Explore and learn)";
$n = 2;
$result = moveNthWordToEndOfString($s, $n);
echo $result . PHP_EOL;
/*
run:
Would you to know more? (Explore and learn) like
*/