How to reverse each word in a string with PHP

1 Answer

0 votes
function reverseEachWordInAString($s) {
    // Split the string into words
    $words = explode(" ", $s);

    // Reverse each word
    $reversedWords = array_map(function($word) {
        return strrev($word);
    }, $words);

    // Join the reversed words back into a string
    return implode(" ", $reversedWords);
}

$s = "java c++ rust python c# php";

echo reverseEachWordInAString($s);



/*
run:

avaj ++c tsur nohtyp #c php

*/

 



answered Sep 24, 2025 by avibootz
...