How to move a word to the end of a string in PHP

1 Answer

0 votes
<?php

function move_word_to_end(string $s, string $word): string {
    // Split on any whitespace
    $parts = preg_split('/\s+/', $s);

    // Remove the first occurrence of the word
    $index = array_search($word, $parts, true);
    if ($index !== false) {
        unset($parts[$index]);
        $parts[] = $word;       // append at the end
        $parts = array_values($parts); // reindex after unset
    }

    return implode(' ', $parts);
}

$s = "Would you like to know more? (Explore and learn)";
$word = "like";

$result = move_word_to_end($s, $word);
echo $result;



/*
run:

Would you to know more? (Explore and learn) like

*/

 



answered Feb 4 by avibootz
...